python - 从类内部调用静态方法

标签 python static-methods

<分区>

从类内部(包含静态方法)调用静态方法时,可以通过以下方式完成:
Class.method() 或 self.method()
有什么区别?
每个都有哪些独特的用例?

class TestStatic(object):
    @staticmethod
    def do_something():
        print 'I am static'

    def use_me(self):
        self.do_something() # 1st way
        TestStatic.do_something() # 2nd way

t = TestStatic()
t.use_me()

打印

I am static
I am static

最佳答案

通过使用 TestStatic.do_something(),您可以绕过子类上的任何覆盖:

class SubclassStatic(TestStatic):
    @staticmethod
    def do_something():
        print 'I am the subclass'

s = SubclassStatic()
s.use_me()

将打印

I am the subclass
I am static

这可能是您想要的,也可能不是。选择最符合您期望的方法。

关于python - 从类内部调用静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28100078/

相关文章:

python - 如何使用numpy降序排序?

python - 使用函数输出作为另一个函数的输入

python - 使 pandas 数据框按计数分组并具有列名

java - 有一个静态方法在枚举中使用非静态成员

php - 确定闭包在 PHP 中是否是静态的

python - Django 中的无限递归/嵌套类别树

python - PyCharm 中的垂直线是什么?

python - Pytest 不收集静态方法

javascript - Javascript 中静态函数声明和普通函数声明的区别?

PHP:保留静态方法并保持可测试性