gpt4 book ai didi

python - 基类方法的重写方法调用如何工作?

转载 作者:IT老高 更新时间:2023-10-28 20:24:54 24 4
gpt4 key购买 nike

根据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.

这是怎么发生的?有人可以用一个简单的例子来说明这个概念吗?

最佳答案

这是您要求的示例。这会打印出 chocolate

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"

字符串 chocolate 被打印而不是 foo 因为 Derived 覆盖了 foo() 函数。尽管 bar() 是在 Base 中定义的,但它最终还是调用了 foo()Derived 实现Base 实现。

关于python - 基类方法的重写方法调用如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41236190/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com