UncleZeiv UncleZeiv - 7 months ago 10
Python Question

How to call a property of the base class if this property is being overwritten in the derived class?

I'm changing some classes of mine from an extensive use of getters and setters to a more pythonic use of properties.

But now I'm stuck because some of my previous getters or setters would call the corresponding method of the base class, and then perform something else. But how can this be accomplished with properties? How to call the property getter or setter from the base class?

Of course just calling the attribute itself gives infinite recursion.

class Foo(object):

@property
def bar(self):
return 5

@bar.setter
def bar(self, a):
print a

class FooBar(Foo):

@property
def bar(self):
# return the same value
# as in the base class
return self.bar # --> recursion!

@bar.setter
def bar(self, c):
# perform the same action
# as in the base class
self.bar = c # --> recursion!
# then do something else
print 'something else'

fb = FooBar()
fb.bar = 7

Answer

You might think you could call the base class function which is called by property:

class FooBar(Foo):

    @property
    def bar(self):
        # return the same value
        # as in the base class
        return Foo.bar(self)

Though this is the most obvious thing to try I think - it does not work because bar is a property, not a callable.

But a property is just an object, with a getter method to find the corresponding attribute:

class FooBar(Foo):

    @property
    def bar(self):
        # return the same value
        # as in the base class
        return Foo.bar.fget(self)
Comments