关于这里关于python的绑定和未绑定方法的first answer,我有一个问题:
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()
产生输出:
Called method_one
Called method_two
Called method_two
Called method_two
有没有办法在python中重写静态方法?
我希望b_test.method_three()
打印“T2”,但它没有(而是打印“Called method_two”)。
在您使用的表单中,您显式地指定要调用的类的静态
method_two
。如果method_three
是一个类方法,并且您调用了cls.method_two
,您将得到您想要的结果:此外,如果要在不使用实例的情况下调用“virtual static”函数,可以如下进行:
在基类非静态中声明函数,如下所示:
通过传递类类型(不是实例)调用它,如下所示:
注意,如果您有一个只在运行时才知道的变量“class_type”,则此选项非常有用。
您看到的行为是预期的行为。静态方法是。。。静态的。当您调用
Test
中定义的method_three()
时,它肯定会调用Test
定义的method_two()
。至于如何“绕开”这种正当的行为。。。
最好的方法是在需要虚拟行为时使方法成为虚拟的。如果你被某个库代码和一个你希望是虚拟的静态方法纠缠在一起,那么你可能会更深入地去看看是有原因还是只是疏忽。
否则,可以在
T2
中定义一个新的method_three()
,它调用T2.method_two()
。相关问题 更多 >
编程相关推荐