我如何访问超类的classmethod?

时间:2013-02-15 11:45:25

标签: python class

我真的需要从超类的子类中找到超类的类方法。

这里是通用代码:

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的classmethod。从A开始,我也称之为未初始化的班级B或{{1}}(遍历MRO)的班级方法。

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

您需要在cls电话中加入super变量:

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

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