I'm running into a silly issue that I can't figure out. If I assign an attribute to a lambda function via setattr
in a for loop, it will assign all the attributes the same value as that which was passed in the last iteration of the loop. Can anyone shed some light on this?
class bee(object):
def __init__(self):
def say_my_name (self, name):
return name
setattr(bee, f'Jim_name', property(lambda self: say_my_name(self, 'Jim')))
setattr(bee, f'Jill_name', property(lambda self: say_my_name(self, 'Jill')))
for name in ['Jake', 'Jordan']:
setattr(bee, f'{name}_name', property(lambda self: say_my_name(self, name)))
buzz = bee()
print(buzz.Jim_name)
# >Jim
print(buzz.Jill_name)
# >Jill
print(buzz.Jake_name)
# >Jordan
# Should be Jake!
print(buzz.Jordan_name)
# >Jordan