rainer
rainer

Reputation: 7099

Python: Overriding a member with a property?

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?

Upvotes: 1

Views: 208

Answers (1)

mgilson
mgilson

Reputation: 309861

This doesn't work because you aren't using a new-style class. Properties are descriptors which only work on new-style classes. What your code is doing is this:

You create a class Derived with a class attribute foo. Then when you create an instance of the class, Base.__init__ takes over since Derived has no __init__ and you add the instance attribute foo which takes precedence to the class attribute.

If you change:

class Base: #old style class

to:

class Base(object):  #new style class

You'll run into an entirely new problem, mainly that your property doesn't have an appropriately defined setter, so when you do self.foo = 1 in Base.__init__ you'll get an AttributeError

Upvotes: 8

Related Questions