从基类调用派生类中的重写方法

2024-04-25 22:29:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我在阅读关于classes的Python文档时遇到了这一段,但我不确定:

Derived classes may override methods of their base classes. Because methods have no special privileges when calling other methods of the same object, a method of a base class that calls another method defined in the same base class may end up calling a method of a derived class that overrides it. (For C++ programmers: all methods in Python are effectively virtual.)

示例:

class A:
    def foo(self):
        self.bar()

    def bar(self):
        print "from A"

class B(A):
    def foo(self):
        self.bar()

    def bar(self):
        print "from B"

这是否意味着类Aobj = A()的对象可以以某种方式结束打印“from B”?我读对了吗?如果这不合理,我道歉。对于python如何处理继承和重写,我有点困惑。谢谢!


Tags: ofthefromselfbasethatdefbar
3条回答
a = A()
a.foo()
b = B()
b.foo()
a.bar = b.bar
a.foo()

输出:

from A
from B
from B

不,这意味着如果您有以下对象:

class B(A):
    def bar(self):
        print "from B"

你也知道

obj = B()
obj.foo()

然后将from B打印为foo()(在基类中定义),调用bar()(也在基类中定义),但在派生类中重写。

至少我是这样读的。

不,超类不可能知道子类的任何信息。它的意思是,如果你实例化子类B,它继承了一个方法foo(),并重写了一个方法bar(),那么当你调用foo()时,它将调用B中的bar()定义,而不是a中的bar()定义。这不是超类编写器想要的-他希望对bar()的调用转到他自己的定义。

相关问题 更多 >