Dynamically creating class properties
Paul Hankin
paul.hankin at gmail.com
Thu Oct 4 18:55:42 EDT 2007
On Oct 4, 9:59 pm, Karlo Lozovina <_karlo_ at _mosor.net> wrote:
> Hi all,
>
> this is my problem: lets say I have a arbitrary long list of attributes
> that I want to attach to some class, for example:
>
> l = ['item1', 'item2', 'item3']
>
> Using metaclasses I managed to create a class with those three
> attributes just fine. But now I need those attributes to be properties,
> so for example if 'A' is my constructed class, and 'a' an instance of
> that class:
>
> a = A()
>
> Now if I write:
>
> a.item1 = 'something'
> print a.item1
>
> I want it to be actually:
>
> a.setitem1('something')
> print a.getitem1
>
> Any idea how to do that with metaclasses and arbitrary long list of
> attributes? I just started working with them, and it's driving me nuts :).
No metaclasses, but how about this?
def make_class(name, attributes):
# Build class dictionary.
d = dict(_attributes=list(attributes))
# Add in getters and setters from global namespace.
for attr in attributes:
d[attr] = property(globals()['get' + attr],
globals()['set' + attr])
# Construct our class.
return type(name, (object,), d)
# Test code:
def getitem1(self):
return self._fred + 1
def setitem1(self, value):
self._fred = value
A = make_class('A', ['item1'])
a = A()
a.item1 = 19
print a.item1
>> 20
You didn't say where the getters and setters (here 'getitem1',
'setitem1', etc.) come from. I've assumed from the global namespace
but you probably want to change that.
--
Paul Hankin
More information about the Python-list
mailing list