generate properties code in class dynamically

JamesEM james.housden at deutsche-boerse.com
Thu May 12 09:11:42 EDT 2011


Hello,
I have a python class that contains a dictionary.
I would like to use python properties to access the elements of the
dictionary.
This could be achieved as follows:

class MyClass(object):

    def __init__(self):
        self.d = {}
        d['field1'] = 1.0
        d['field2'] = 'A'
        d['field3'] = [10.0,20.0,30.0]

    @property
    def field1(self):
        return self.d['field1']

    @field1.setter
    def field1(self, value):
        self.d['field1'] = value

    @field1.deleter
    def field1(self):
        del self.d['field1']

    @property
    def field2(self):
        return self.d['field2']

    @field1.setter
    def field2(self, value):
        self.d['field2'] = value

    @field1.deleter
    def field2(self):
        del self.d['field2']

    @property
    def field3(self):
        return self.d['field3']

    @field3.setter
    def field3(self, value):
        self.d['field3'] = value

    @field3.deleter
    def field3(self):
        del self.d['field3']


However, I am effectively writing the same properties code three
times.
I would prefer to generate the properties code dynamically from the
keys of the dictionaries.
What I am looking for is something like:

class MyClass(object):

    def __init__(self):
        self.d = {}
        d['field1'] = 1.0
        d['field2'] = 'A'
        d['field3'] = [10.0,20.0,30.0]
        for f in d:
           create_property(f)


where create_property(f) dynamically creates the property code for
field f in MyClass.

Is this possible?
If so, how could I do it?

Thanks,
James



More information about the Python-list mailing list