Adding properties to objects
John Roth
newsgroups at jhrothjr.com
Tue Apr 13 13:50:40 EDT 2004
"Matthew Barnes" <matthew at barnes.net> wrote in message
news:3a8e83d2.0404130906.2ea796e9 at posting.google.com...
> Is it possible to add properties to objects dynamically?
>
> I have an instance (x) of some new-style class (Foo), and I would like
> to be able to do something like:
>
> >>> x = Foo()
> >>> x.myproperty = property(getsomething, setsomething, delsomething);
> >>> x.myproperty # invokes getsomething
> >>> x.myproperty = 1 # invokes setsomething
> >>> del x.myproperty # invokes delsomething
>
> However, when I evaluate x.myproperty I get back a property object
> (which makes sense). I get the feeling I'm missing a step to "bind"
> the property object to the class instance.
>
> Is this possible (it's Python... of course it's possible, right?), and
> if so, how?
The property definition only lives in a class; you cannot add
a property to an instance by itself. Well, you can but it won't
be evaluated as a property by the default __getattribute__()
magic method.
To make a property work on an instance basis you'd have
to have a specialty __getattribute__() magic method in the
class. That's left as an exercise for the reader.
John Roth
>
> Matthew Barnes
More information about the Python-list
mailing list