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中的静态方法


基础教程推荐
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01