gpt4 book ai didi

Python super 覆盖对象名称

转载 作者:太空宇宙 更新时间:2023-11-03 11:49:47 24 4
gpt4 key购买 nike

我正在尝试扩展一个框架,我有这样的东西:

class A(object):
def test(self):
print(1)


class B(object):
def method(self):
a = A()
a.test()


class CustomA(A):
def test(self):
print(2)


class C(B):

def method(self):
A = CustomA
super(C, self).method()

c = C()
c.method()

A 类和 B 类来自框架。

我想从 A 编辑这个 test(),并让 C 使用这个新方法。

例如,在这段代码中,如何让我的代码打印 2 而不是 1?

[更新]

这只是一个简单的例子。我想延长 this class .因此,与其创建 SettingsPanel,不如创建一个 CustomSettingsPanel

但问题是我需要用很多类来完成它,所以我只想要一种方法让 python 始终使用 CustomSettingsPanel 而不是 SettingsPanel .

最佳答案

您不需要在 C 中调用 super。您正在尝试覆盖 B 的方法。

class A(object):
def test(self):
print(1)


class B(object):
def method(self):
a = A()
a.test()


class CustomA(A):
def test(self):
print(2)


class C(B):
def method(self):
A = CustomA()
A.test()

c = C()
c.method()

关于Python super 覆盖对象名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30564216/

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