静态继承python

Syd*_*ove 2 python

我正试图让某种静态继承发生.下面的代码打印"nope".我不确定如何解释自己,但我想要的是A类使用B的方法(如果存在的话).

class A(object):
    @staticmethod
    def test():
       print("nope")

    @staticmethod
    def test2():
        __class__.test()

class B(A):
    @staticmethod
    def test():
        print("It Works")

    @staticmethod
    def run():
        __class__.test2()


if __name__ == "__main__":
    B.run()
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 6

__class__作为闭包引用从未打算用作对当前实例类型的引用; 它总是引用你定义方法的类(例如Afor A.test2).它是super()函数使用的内部实现细节.不要在这里使用它.

使用@classmethod代替;

class A(object):
    @classmethod
    def test(cls):
       print("nope")

    @classmethod
    def test2(cls):
        cls.test()

class B(A):
    @classmethod
    def test(cls):
        print("It Works")

    @classmethod
    def run(cls):
        cls.test2()


if __name__ == "__main__":
    B.run()
Run Code Online (Sandbox Code Playgroud)