简体   繁体   中英

Python super: calling a base class method which contains another base class method that is overriden by derived class

class A(object):
    def foo(self):
        print "A - foo"
    def foo2(self):
        print "foo2"
        self.foo()

class B(A):
    def foo(self):
        print "B - foo"
    def foo2(self):
        super(B, self).foo2()

B().foo2()

I was trying to get [senario1]:

foo2
A - foo

but got [senario2]:

foo2
B - foo

instead.

I found the explanation , but I am wondering if there is a way that yields [senario1] without changing the name of method foo in class A ?

One way to do this is to call foo on A and pass self to it by hand:

class A(object):
    def foo(self):
        print("A - foo")
    def foo2(self):
        print("foo2")
        A.foo(self)

class B(A):
    def foo(self):
        print("B - foo")
    def foo2(self):
        super(B, self).foo2()

B().foo2()

This way you will always call foo on A . If this foo would call self.foo() , if would again call B s foo method.

As Leon pointed out you could simply access the foo method inside the A class by hardcoding the explicit call via A.foo and passing instance object as argument, however as Rawing has stated it's not good solution. Actually it's example of wrong class design. Why?

  1. Imagine that in a larger project you would use explicit calls via A.foo in hundreds of places. Now, try to rename your A class to MagicUnicorn class.

  2. It's counter-intuitive. If you override the foo method from A in B then the foo from A is not needed in 99.9999% cases as there must be a reason to override it.

A better solution rather than using explicit calls would be to rename the foo in B (as Rawing has said):

class A(object):
    def foo(self):
        print "A - foo"
    def foo2(self):
        print "foo2"
        self.foo()

class B(A):
    def unicorn_foo(self):
        print "B - foo"
    def foo2(self):
        super(B, self).foo2()

B().foo2()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM