I have a question about python inherited class method, in the following code.
class B(object):
def test(self):
self.call()
def call(self):
print("Call from B")
if __name__ == "__main__":
b = B()
b.test()
from b import B
class C(B):
def call(self):
print("Call from C")
if __name__ == "__main__":
c = C()
c.test()
When I run this code, the result is
Call from C
The parent class method will call children's method. I want to know if it is an expected and stable behaviour? Because I also try the same logic in C++, it will print
Call from B
Yes, this is expected. c
is an instance of C
, but since C.test
is not defined, c.test
resolves to B.test
. However, the corresponding call to self.call()
invokes C.call
because the runtime type of self
is C
, not B
, and C.call
is defined. Think of all Python methods as being virtual methods.
As a complement to chepner's answer, this C++ code exhibits the exact same behaviour as you have in Python:
#include <iostream>
class B {
public:
void test() {
call();
}
virtual void call() {
std::cout << "Called from B" << std::endl;
}
};
class C: public B {
public:
void call() {
std::cout << "Called from C" << std::endl;
}
};
int main() {
C c;
c.test(); // will print Called from C
return 0;
}
If you come from C++ think that all members are public, and all methods virtual.
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.