problem with defining setters and getters

John Hunter jdhunter at
Wed Mar 12 17:04:23 CET 2003

I have a class that is initialized with another object that has
certain attributes I want to expose to the class with getters and
setters.  I am doing this

class Entry:
    def __init__(self): = 1
        self.somevar = 2

    def get_field_names(self):
        return ['pid', 'somevar']
class MyClass:
    def __init__(self, entry):
        self.entry = entry

        for name in entry.get_field_names():
            def get_func(): return getattr(self.entry,  name)
            def set_func(val): return setattr(self.entry, name, val)
            setattr(self, 'get_' + name, get_func)
            setattr(self, 'set_' + name, set_func)


entry = Entry()
c = MyClass(entry)

print c.get_pid()

entry has a function get_field_names that returns a list of attributes
that I want to expose.  pid is one of those attributes, and I am
calling set_pid and get_pid as a test case.

The problem is that all of the getters and setters take on the last
attribute returned by field names.  That is, get_pid returns 'John' in
the example above, and I want it to return 1.  It appears that there
is only one get_func in the __init__ loop, and all of the getters are
using this func.  Likewise for set_func.

Suggestions to fix this and explanations welcome.

John Hunter

python 2.2

More information about the Python-list mailing list