【问题标题】:Correct/preferred way to access staticmethod from within class instance从类实例中访问 staticmethod 的正确/首选方式
【发布时间】:2019-11-25 21:37:19
【问题描述】:

从 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)

是否有任何理由偏爱一种方式而不是另一种方式?

【问题讨论】:

  • 我这样做的方法是在另一个方法中使用 self.div_2 并从类外部使用 Foo.div_2。

标签: python class oop static-methods


【解决方案1】:

两者做不同的事情: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

【讨论】:

  • 谢谢,这是我没想到的一个有趣的考虑因素。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 2015-07-09
  • 1970-01-01
  • 2018-06-15
  • 2017-05-12
  • 1970-01-01
相关资源
最近更新 更多