Dynamically creating class properties
Paul Hankin
paul.hankin at gmail.com
Thu Oct 4 19:11:14 EDT 2007
On Oct 4, 11:55 pm, Paul Hankin <paul.han... at gmail.com> wrote:
> 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)
Sorry, I'm adding '_attributes' unnecessarily to the class dictionary.
The dictionary should be just initialised with d = {} before the
properties are added.
--
Paul Hankin
More information about the Python-list
mailing list