Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 428
blueFast Avatar asked Jun 24 '26 14:06

blueFast


1 Answers

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.

like image 190
RichieHindle Avatar answered Jun 26 '26 04:06

RichieHindle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!