Generate a new callback function for each unit instance. In the example below, each instance has its own lambda function that is assigned to func. Each lambda function remembers the instance's label as the argument's default value.
>>> class unit(object): def __init__(self, label): self.func = lambda x=label: another_function(x) >>> def another_function(x): print x >>> u1 = unit(1) >>> u2 = unit(2) >>> u1.func() 1 >>> u2.func() 2 Jason ________________________________ From: Herman <amberautumnameth...@gmail.com> To: pygame-users@seul.org Sent: Wed, June 2, 2010 3:18:03 AM Subject: [pygame] Writing a simple GUI Hi everyone, I've just started learning Pygame (wrote a tetris game) and currently I'm trying to write a simple turn-based strategy game, similar to Advance Wars. What I need to implement now is a simple GUI system which essentially provides menus to select what each unit does. I decided to try to have a Tmenu class which consists of several Toption instances (each one representing a menu option). The Toption basically consists of a "label" member, a "image" member and a "func" member. The func member is supposed to be a function that will be executed when that specific option is selected. But if I wanted to say, have an option for the selected unit to attack an adjacent unit, the function I assigned to "func" couldn't possibly know which unit is attacking which (since the arguments between different functions should vary). I thought about having a global variable that stores arguments that the function could access but that seems to complicate the code and I read that global variable use should be minimized. So I'm wondering if someone could show me how I could solve this problem so that the each menu option's function will have the information it needs when it executes?