我真的需要从超类的子类中找到超类的类方法。
下面是通用代码:
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的classmethod。在C中,我还调用了未初始化的类A或B (遍历MRO)的类方法。
我如何才能做到这一点?
发布于 2013-02-15 19:49:09
您需要在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()https://stackoverflow.com/questions/14894030
复制相似问题