Adding properties to objects
Robert Brewer
fumanchu at amor.org
Tue Apr 13 14:14:33 EDT 2004
John Roth wrote:
> "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
>
> 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.
However, Matthew, you can dynamically add a property to the *class*,
e.g.:
class Property(object):
def __get__(self, obj):
pass
def __set__(self, obj, value):
pass
Foo.setattr(propertyname, Property())
...read Raymond Hettinger's How-To Guide for Descriptors to make your
own property classes:
http://users.rcn.com/python/download/Descriptor.htm
Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org
More information about the Python-list
mailing list