Why property works only for objects?
Alex Martelli
aleaxit at yahoo.com
Fri Mar 10 01:54:05 EST 2006
Michal Kwiatkowski <ruby at no.spam> wrote:
...
> The problem is I have an instance of a given class (say BaseClass) and I
> want it to implement some attribute accesses as method calls. I'm not a
> creator of this object, so changing definition of BaseClass or
> subclassing it is not an option.
Wrong! Of _course_ it's an option -- why do you think it matters at all
whether you're the creator of this object?!
> Code below doesn't work, but shows my
> intention:
>
> # obj is instance of BaseClass
> def get_x(self):
> # ...
> def set_x(self, value):
> # ...
> obj.x = property(get_x, set_x)
def insert_property(obj, name, getter, setter):
class sub(obj.__class__): pass
setattr(sub, name, property(getter, setter))
obj.__class__ = sub
See? Of COURSE you can subclass -- not hard at all, really.
Alex
More information about the Python-list
mailing list