gpt4 book ai didi

python - 如何访问父类(super class)的类方法?

转载 作者:太空宇宙 更新时间:2023-11-04 06:17:05 24 4
gpt4 key购买 nike

我真的需要从该父类(super class)的子类中找到父类(super class)的 classmethod 的一些方法。

这是通用代码:

class A(object):
def __init__(self):
print "A init"

@classmethod
def _method(cls):
print cls
return cls()


class B(A):
def __init__(self):
print "B init"

class C(B):
def __init__(self):
print "C init"

@classmethod
def _method(cls):
print "calling super(C)'s classmethod"
return super(C)._method()

c = C._method()

结果是:

Traceback (most recent call last):
File "C:/Python27x64/testclass", line 26, in <module>
c = C._method()
File "C:/Python27x64/testclass", line 22, in _method
return super(C)._method()
AttributeError: 'super' object has no attribute '_method'

请注意,在 c = C._method() 中,我正在调用未初始化的类 C 的类方法。从 C,我还调用了未初始化的类 AB(遍历 MRO)的类方法。

我怎样才能做到这一点?

最佳答案

您需要在 super 调用中包含 cls 变量:

class C(B):
def __init__(self):
print "C init"

@classmethod
def _method(cls):
print "calling super(C)'s classmethod"
return super(C, cls)._method()

关于python - 如何访问父类(super class)的类方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14894030/

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