python – 如何从基类方法调用重写方法? - 代码日志

python – 如何从基类方法调用重写方法?

根据docs on inheritance

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.

怎么会这样呢?有人可以用简单的例子来说明这个概念吗?

以下是您请求的示例。这打印巧克力。

class Base:
    def foo(self):
        print("foo")
    def bar(self):
        self.foo()

class Derived(Base):
    def foo(self):
        print("chocolate")

d = Derived()
d.bar()  # prints "chocolate"

字符串巧克力被打印而不是foo,因为派生覆盖了foo()函数。即使在Base中定义了bar(),它最终调用了foo()的Derived实现,而不是Base实现。

http://stackoverflow.com/questions/41236190/how-do-overridden-method-calls-from-base-class-methods-work

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:python – 如何从基类方法调用重写方法?