This question is similar to this other one, with the difference that the data member in the base class is not wrapped by the descriptor protocol.
In other words, how can I access a member of the base class if I am overriding its name with a property in the derived class?
class Base(object):
def __init__(self):
self.foo = 5
class Derived(Base):
def __init__(self):
Base.__init__(self)
@property
def foo(self):
return 1 + self.foo # doesn't work of course!
@foo.setter
def foo(self, f):
self._foo = f
bar = Base()
print bar.foo
foobar = Derived()
print foobar.foo
Please note that I also need to define a setter because otherwise the assignment of self.foo in the base class doesn’t work.
All in all the descriptor protocol doesn’t seem to interact well with inheritance…
Defining
in
Basemakesfooa member (attribute) of the instance, not of the class. The classBasehas no knowledge offoo, so there is no way to access it by something like asuper()call.This is not necessary, however. When you instanciate
and the
__init__()method of the base class callsthis will not result in the creation / overwriting of the attribute, but instead in
Derived‘s setter being called, meaningand thus
self._foo = 5. So if you putin your getter, you pretty much get what you want. If you need the value that
self.foois set to inBase‘s constructor, just look at_foo, which was set correctly by the@foo.setter.