【问题标题】:Python inherited class behaviourPython 继承的类行为
【发布时间】:2018-11-10 23:42:20
【问题描述】:

我有一个关于python继承类方法的问题,在下面的代码中。

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()

当我运行这段代码时,结果是

Call from C

父类方法会调用子类方法。我想知道这是否是预期和稳定的行为?因为我也在C++中尝试过同样的逻辑,所以会打印出来

Call from B

【问题讨论】:

  • 你的问题是关于Python是否具有多态性?如果是这样the answer is yes it does
  • 感谢您的回复。我只是想知道为什么 C++ 和 python 之间存在差异。
  • 为什么 C++ 和 python 之间存在差异”因为它们是 2 种不同的语言,而且功能完全不必完全相同。

标签: python inheritance


【解决方案1】:

是的,这是意料之中的。 cC 的一个实例,但由于未定义 C.testc.test 解析为 B.test。但是,对self.call() 的相应调用会调用C.call,因为selfruntime 类型是C,而不是B,并且C.call 定义。将所有 Python 方法都视为虚拟方法。

【讨论】:

    【解决方案2】:

    作为对 chepner 答案的补充,此 C++ 代码的行为与您在 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;
    }
    

    如果你来自 C++,认为所有成员都是公共的,所有方法都是虚拟的。

    【讨论】:

    • 谢谢;我花了 20 分钟试图写出大致相同的东西;)(只是我使用了C *c = new C();,错误地认为指针在某种程度上是调用虚方法行为所必需的。)
    • 谢谢,我知道为什么我在 C++ 中没有得到相同的结果,我忘记使用关键字 virtual。
    猜你喜欢
    • 1970-01-01
    • 2011-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-28
    • 2015-09-04
    • 1970-01-01
    相关资源
    最近更新 更多