Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #5239
| From | nn <pruebauno@latinmail.com> |
|---|---|
| Newsgroups | comp.lang.python |
| Subject | Re: generate properties code in class dynamically |
| Date | 2011-05-12 07:14 -0700 |
| Organization | http://groups.google.com |
| Message-ID | <922112f8-956f-49da-9a95-fd2eccd4911f@l30g2000vbn.googlegroups.com> (permalink) |
| References | <f5a65253-def8-41c8-b722-97cd76bc72d0@32g2000vbe.googlegroups.com> |
On May 12, 9:11 am, JamesEM <james.hous...@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/
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
generate properties code in class dynamically JamesEM <james.housden@deutsche-boerse.com> - 2011-05-12 06:11 -0700
Re: generate properties code in class dynamically nn <pruebauno@latinmail.com> - 2011-05-12 07:14 -0700
Re: generate properties code in class dynamically Terry Reedy <tjreedy@udel.edu> - 2011-05-12 16:04 -0400
Re: generate properties code in class dynamically JamesEM <james.housden@deutsche-boerse.com> - 2011-05-12 22:45 -0700
csiph-web