在python中重写静态方法 [英] Overriding a static method in python
本文介绍了在python中重写静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请参考第一个答案关于python的绑定和未绑定方法,我有一个问题:
Referring to the first answer about python's bound and unbound methods here, I have a question:
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中的静态方法?
Is there a way to override a static method in python?
我希望b_test.method_three()
打印"T2",但不会(打印"Called method_two").
I expected b_test.method_three()
to print "T2", but it doesn't (prints "Called method_two" instead).
推荐答案
在此处使用的形式中,您明确指定了要调用的类的静态method_two
.如果method_three
是类方法,并且您调用了cls.method_two
,则将获得所需的结果:
In the form that you are using there, you are explicitly specifying what class's static method_two
to call. If method_three
was a classmethod, and you called cls.method_two
, you would get the results that you wanted:
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
这篇关于在python中重写静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文