我真的需要从该父类(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,我还调用了未初始化的类 A 或 B(遍历 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()
