S
Steven D'Aprano
Question out of general interest in the language: If I would want to
generate such functions in a for-loop, what would I have to do? This
doesn't work:
class Move(object):
def __call__(self, direction):
return direction
move = Move()
for f in ['up', 'down', 'right', 'left']:
move.__dict__[f] = lambda: move(f)
... because now 'move.up()' returns 'left' because thats the current
value of f. Is there a way to 'expand' f in the loop? Or a reason that
you never should use this?
Possibly the simplest way is to use Python's handling of default values
to get the result you want:
for f in ['up', 'down', 'right', 'left']:
move.__dict__[f] = lambda f=f: move(f)
BTW, there's no need to explicitly reference move.__dict__:
for f in ['up', 'down', 'right', 'left']:
setattr(move, f, lambda f=f: move(f))