如何从基类方法调用重写方法? [英] How do overridden method calls from base-class methods work?

查看:208
本文介绍了如何从基类方法调用重写方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据继承文档


派生类可以覆盖其基类的方法。因为方法在调用同一对象的其他方法时没有特殊权限,所以调用同一基类中定义的另一个方法的基类方法最终可能会调用覆盖它的派生类的方法。

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.

这是怎么回事?有人可以通过一个简单的例子来说明这个概念吗?

How does that happen? Can someone illustrate this concept with a simple example?

推荐答案

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

Here's the example you requested. This prints 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 因为派生会覆盖 foo()函数。即使 bar() Base 中定义,它最终会调用 Derived 实现 foo()而不是 Base 实现。

The string chocolate is printed instead of foo because Derived overrides the foo() function. Even though bar() is defined in Base, it ends up calling the Derived implementation of foo() instead of the Base implementation.

这篇关于如何从基类方法调用重写方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆