简体   繁体   中英

Python 3 inheritance same as in C++

I have:

class A:

    def __init__(self):
        pass

    def func_X(self):
        print("Class A: X")

        self.func_Y()

    def func_Y(self):
        print("Class A: Y")
        print("Why does not work?")


class B(A):

    def __init__(self):
        A.__init__(self)

    def func_Y(self):
        print("Class B: Y")


if __name__ == "__main__":

    TEST = B()
    TEST.func_X()

OUTPUT:

Class A: X
Class B: Y

Question: Why works "B.func_Y", but not "A.func_Y"? This is bug? How to fix it? I need this to work same as in C++. C++ analog:

#include <iostream>

using namespace std;

class A
{
public:
      void func_X() {cout<<"Class A: X"<<endl; func_Y();}
      void func_Y() {cout<<"Class A: Y"<<endl;}
};

class B: public A
{
public:
      void func_Y() {cout<<"Class B: Y"<<endl;}
};


int main(void)
{
    B TEST = B();
    TEST.func_X();

    return 0;
}

OUTPUT:

Class A: X
Class A: Y

I faced this problem for a long time, but have not found a solution. Any idea how to solve this problem?

This happens because you call func_Y() on self . This would probably be the equivalent in C++ of calling func_Y() on this .

Look at this related question .

It seems that you should do a A.func_Y() or a call to super instead of self.func_Y() .

Let me know if this helps you.

Python resolves everything at run time, using the dynamic type. C++ resolves almost everything at compile time, using the static type. If you want dynamic type resolution, you must tell the compiler this in the static type . In this case, declare func_Y virtual in the base class, and it should work as in Python.

The way name lookup works is actually significantly different in Python and in C++, but in simple cases, the practical results are as if all members in Python were declared virtual in C++. Except that in C++, only functions can be declared virtual; in Python, dynamic lookup affects all members.

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