覆盖python中的静态方法

Emm*_*mma 46 python static overriding

在这里参考关于python的绑定和未绑定方法的第一个答案,我有一个问题:

class Test:
    def method_one(self):
        print "Called method_one"
    @staticmethod
    def method_two():
        print "Called method_two"
    @staticmethod
    def method_three():
        Test.method_two()
class T2(Test):
    @staticmethod
    def method_two():
        print "T2"
a_test = Test()
a_test.method_one()
a_test.method_two()
a_test.method_three()
b_test = T2()
b_test.method_three()
Run Code Online (Sandbox Code Playgroud)

产生输出:

Called method_one
Called method_two
Called method_two
Called method_two
Run Code Online (Sandbox Code Playgroud)

有没有办法在python中覆盖静态方法?

我希望b_test.method_three()打印"T2",但它没有(打印"Called method_two"代替).

los*_*gic 64

在您使用的表单中,您明确指定method_two要调用的类的静态.如果method_three是一个类方法,并且你打电话cls.method_two,你会得到你想要的结果:

class Test:
    def method_one(self):
        print "Called method_one"
    @staticmethod
    def method_two():
        print "Called method_two"
    @classmethod
    def method_three(cls):
        cls.method_two()

class T2(Test):
    @staticmethod
    def method_two():
        print "T2"

a_test = Test()
a_test.method_one()  # -> Called method_one
a_test.method_two()  # -> Called method_two
a_test.method_three()  # -> Called method_two

b_test = T2()
b_test.method_three()  # -> T2
Test.method_two()  # -> Called method_two
T2.method_three()  # -> T2
Run Code Online (Sandbox Code Playgroud)

  • 真有用.就我而言,我需要访问一个实例的类.我是这样做的:`instance .__ class __.my_method()` (4认同)