generate properties code in class dynamically

nn pruebauno at latinmail.com
Thu May 12 10:14:36 EDT 2011


On May 12, 9:11 am, JamesEM <james.hous... at deutsche-boerse.com> wrote:
> 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

Some searching in the cookbook should help. I found this:

http://code.activestate.com/recipes/577590-dictionary-whos-keys-act-like-attributes-as-well/



More information about the Python-list mailing list