首页 > 解决方案 > 从类实例中访问 staticmethod 的正确/首选方式

问题描述

当从 Python 类中的常规实例方法访问静态方法时,有 2 个不同的选项似乎都有效 - 通过self对象访问和通过类名本身访问,例如

class Foo:

    def __init__(self, x: int):
        self.x = x

    @staticmethod
    def div_2(x: int):
        return x / 2

    def option_1(self):
        return Foo.div_2(self.x)

    def option_2(self):
        return self.div_2(self.x)

有什么理由比另一种方式更喜欢一种方式吗?

标签: pythonclassoopstatic-methods

解决方案


两者做不同的事情:Foo.div_2调用Foo;的方法 如果self.div_2一个self类的实例派生自Foo

class Bar(Foo):
    @staticmethod
    def div_2(x: int):
        return x * 2

b = Bar(12)
print(b.option_1()) # prints 6.0
print(b.option_2()) # prints 24

推荐阅读