[Modeling-users] dynamic, metaclasses and Virtual properties
Status: Abandoned
Brought to you by:
sbigaret
From: Ernesto R. <er...@si...> - 2004-06-30 16:24:16
|
Hi all, I think that Python has a design error with properties, but it is easy to correct this. We can see that in the following example: class Base(object): _name=None def getName(self): return self._name def setName(self, value): self._name=value name=property(getName,setName) class Sub(Base): def setName(self, value): print "Setting name to '%s'" % value Base.setName(self,value) Ok, here we can see how Sub extends the functionality of Base. But if we do: instance=Sub() instance.name="a name" Sub.setName is NOT called.!!! Of course, it cand, because the property binds directly to the methods. Now we see the Base class corrected, using 'virtual' properties: class Base(object): _name=None def getName(self): return self._name def setName(self, value): self._name=value name=property(lambda s: s.getName(), lambda s, v: s.setName(v)) class Sub(Base): def setName(self, value): print "Setting name to '%s'" % value Base.setName(self,value) An try again: >>> instance=Sub() >>> instance.name="a name" Setting name to 'a name' In Modeling, when inheriting from class created with properties (dynamic), it does NOT the inherited methods. Is this reasonable? Here I have attached a little patch for dynamic.py. I made a local function mkProp, so that variable binding is correct, otherwise it does not work the way it should. Just a remark about the setter. As in the original code, a virtual setter is created only if the attribute is settable in the base class. In this case, we have two alternatives: 1. do not create a setter, as the original code, 2. create always a virtual setter and the setter in the base class raises a ReadOnlyAttributeException. (This is was I have done in a experimental framework.) Best regards, Erny |