覆盖python中的静态方法

Overriding a static method in python(覆盖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中的静态方法

基础教程推荐