blueFast
blueFast

Reputation: 44371

Call base class method when derived class overloads it

I have the following:

class A(object):
    def x(self): print "Hello"
    def y(self): self.x()

class Abis(A):
    def x(self): print "Bye"

a = Abis()
a.x()
a.y()

Which prints:

Bye
Bye

But I actually wanted:

Bye
Hello

Since I want A.y to call the "original" A.x. How can I reference the original A.x in A, when the derived class has overloaded it?

Upvotes: 2

Views: 13692

Answers (2)

RichieHindle
RichieHindle

Reputation: 281485

Like this:

class A(object):
    def x(self): print "Hello"
    def y(self): A.x(self)

...although that's slightly weird. Why are you (or, why is someone) overriding x if you don't want it called in this situation?

If you don't want it overridden, give it a double-underscore prefix:

class A(object):
    def __x(self): print "Hello"
    def y(self): self.__x()

Anyone defining __x in a derived class will get their own unique __x that doesn't override yours - see Private Variables and Class-local References.

Upvotes: 5

Nathan Ernst
Nathan Ernst

Reputation: 4590

You want the "super" function:

super(Abis, self).x ()

This will call "x" on the base class. See: docs.python.org/2/library/functions.html#super

Upvotes: 5

Related Questions