Dynamic methods and lambda functions

unineuro at gmail.com unineuro at gmail.com
Fri Jan 23 07:28:33 EST 2009


Hi,
I want to add some properties dynamically to a class, and then add the
corresponding getter methods. Something resulting in this:

class Person:
    def Getname(self):
        return self.__name

    def Getage(self):
        return self.__age

I've implemented the next code, creating the properties from a list:

props = [
    ("name", "peter"),
    ("age", 31),
    ("wife", "mary")
    ]

class Person:
    def __init__(self):
        for prop in props:
            setattr(self, "__" + prop[0], prop[1])
            setattr(Person, "Get" + prop[0], lambda self: getattr
(self, "__" + prop[0]))


if __name__ == "__main__":

    person = Person()

    print person.__name
    print person.__age
    print person.__wife
    print
    print person.Getname()
    print person.Getage()
    print person.Getwife()


And the resulting execution of this program is:

peter
31
mary

mary
mary
mary

The attributes are right, but the getter are not working. The problem
is that the lambda function always execute the last parameter passed
for all instances of the methods. How could it be done the right way?

Thanks in advance



More information about the Python-list mailing list