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中的静态方法
基础教程推荐
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 筛选NumPy数组 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01