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中的静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:覆盖python中的静态方法
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01