gpt4 book ai didi

python - 如何从继承链中上几层的基类调用方法?

转载 作者:行者123 更新时间:2023-12-01 03:09:05 26 4
gpt4 key购买 nike

假设我们有以下继承链:

class Base:
def method(self):
# …

class Derived1(Base):
def method(self):
# …

class Derived2(Derived1):
pass

class Derived3(Derived2):
def method(self):
# …

问题:我想以某种方式在 Derived3 中定义 method ,以便它从 Base 调用自身。

通常我会写:

class Derived3(Derived2):
super().method()

但这会从 Derived1 调用 method,这正是我想要避免的。我想从 Base 调用 method

最佳答案

最简单的方法是直接调用 Base 方法,显式传递 self:

Base.method(self)

如果目标是跳到“MRO 中一些已知的坏父类(super class)之后的任何内容”,您可以使用带有显式参数的 super 来表现,就像它是从“坏的父类(super class)”调用的一样。 super 类”,因此它移动到“无论接下来发生什么”:

class Derived3(Derived2):
def method(self):
# Call method from next class after Derived1 in MRO, which happens to be Base
# Using super means the method is bound, so self passed implicitly to method
super(Derived1, self).method()

关于python - 如何从继承链中上几层的基类调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43058707/

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