重写Python中的静态方法
参考第一个答案 python的绑定和非绑定方法在这里,我有一个问题:
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
Is there a way to override a static method in python?
我期望 b_test.method_ Three() 打印“T2”,但它没有(而是打印“Called method_two”)。
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()
produces output:
Called method_one
Called method_two
Called method_two
Called method_two
Is there a way to override a static method in python?
I expected b_test.method_three()
to print "T2", but it doesn't (prints "Called method_two" instead).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在您在那里使用的形式中,您明确指定要调用哪个类的静态
method_two
。 如果method_third
是一个类方法,并且您调用了cls.method_two
,您将得到您想要的结果:In the form that you are using there, you are explicitly specifying what class's static
method_two
to call. Ifmethod_three
was a classmethod, and you calledcls.method_two
, you would get the results that you wanted:您看到的行为是预期的行为。 静态方法是...静态的。 当你调用
Test
中定义的method_third()
时,它肯定会调用Test
中定义的method_two()
。至于如何“绕过”这种正确的行为......
最好的方法是当您想要虚拟行为时将方法设为虚拟。 如果您被某些具有静态方法的库代码所困扰,而您希望该静态方法是虚拟的,那么您可能会更深入地了解是否有原因,或者是否只是一个疏忽。
否则,您可以在
T2
中定义一个新的method_two()
来调用T2.method_two()
。The behavior you see is the expected behavior. Static methods are... static. When you call
method_three()
defined inTest
it will certainly callmethod_two()
defined byTest
.As for how to "get around" this proper behavior...
The very best way is to make methods virtual when you want virtual behavior. If you're stuck with some library code with a static method that you wish were virtual then you might look deeper to see if there's a reason or if it's just an oversight.
Otherwise, you can define a new
method_three()
inT2
that callsT2.method_two()
.此外,如果您想在没有实例的情况下调用“虚拟静态”函数,您可以像这样进行:
将基类中的函数声明为非静态,如下所示:
通过传递类类型(不是实例)来调用它,如下所示:
注意,如果您有一个变量“class_type”,该变量仅在运行时已知,则这很有用。
Additionally, if you want to call the "virtual static" function without an instance, you could proceed like so:
Declare the function in the base class non-static like so:
Call it by passing the class type, which is not an instance, like so:
Note, this is useful if you have a variable "class_type", which is only known during run time.