python - 在 Python 中访问类中静态方法的惯用方法

标签 python static-methods

我理解 staticmethod 应该始终通过它们所属的类名来引用。但我发现它们也可以通过关键字 self 访问。

这有点令人困惑,我没有看到解释器抛出错误。

import unittest

class TestA(unittest.TestCase):
    @staticmethod
    def fun1():
        return True

    @staticmethod
    def fun2():
        return False

    def test_one(self):
        assert TestA.fun1() == True

    def test_two(self):
        assert self.fun2() == False

if __name__ == '__main__':
    unittest.main()

访问静态方法的正确方法是什么。就像上面的 TestA.fun1 这对我来说很清楚,或者 self.fun2 这有点令人担忧,因为没有实例发送到 fun2。

最佳答案

任何一种方式都可以接受,如 the documentation 中所述。 :

It can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class.

从某种意义上说,静态方法的要点是允许您调用该方法,而不必担心是在实例上还是在类上调用它。

关于python - 在 Python 中访问类中静态方法的惯用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24334739/

相关文章:

python - 使用枚举返回字典

Python epsilon 不是最小的数

java - 我可以在不使用类名的情况下调用另一个类的静态方法吗?

java - java中直接引用静态嵌套类

Python:识别创建生成器的生成器函数

python - numpy 中矩阵的 One-hot 表示

javascript - 在 Typescript 中访问对象类的静态方法?

java - 为什么当我尝试覆盖静态方法时编译器不提示?

C#:从基类静态方法确定派生对象类型

python - Seaborn 热图 : annotate with clickable hyperlink