I was trying to override a member of a Python (2.7) class with a property, as shown in the following code:
class Base:
def __init__(self):
self.foo = 1
class Derived(Base):
foo = property(lambda self: 2)
print Derived().foo
However, the last line prints 1 instead of 2. From the way I thought properties are supposed to work (ie., easily change a member to a function later on), this seems counter-intuitive to me. Am I missing something? Is there some workaround?
This doesn’t work because you aren’t using a new-style class. Properties are
descriptorswhich only work on new-style classes. What your code is doing is this:You create a class
Derivedwith a class attributefoo. Then when you create an instance of the class,Base.__init__takes over sinceDerivedhas no__init__and you add the instance attributefoowhich takes precedence to the class attribute.If you change:
to:
You’ll run into an entirely new problem, mainly that your property doesn’t have an appropriately defined
setter, so when you doself.foo = 1inBase.__init__you’ll get anAttributeError