Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #5233
| From | JamesEM <james.housden@deutsche-boerse.com> |
|---|---|
| Newsgroups | comp.lang.python |
| Subject | generate properties code in class dynamically |
| Date | 2011-05-12 06:11 -0700 |
| Organization | http://groups.google.com |
| Message-ID | <f5a65253-def8-41c8-b722-97cd76bc72d0@32g2000vbe.googlegroups.com> (permalink) |
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
Back to comp.lang.python | Previous | Next — Next in thread | Find similar
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