python - 从类实例中访问 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)
有什么理由比另一种方式更喜欢一种方式吗?
解决方案
两者做不同的事情: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
推荐阅读
- dictionary - 字符串内的presto lambda函数变量
- c# - 如何在 Xunit 中为集合编写 Assert 语句?
- csv - 将大 csv 文件部分导入 Neo4j
- sql - 在实体框架中使用事务的问题
- javascript - 通过单击图像在一个容器中显示/隐藏不同的信息:隐藏前显示信息
- regex - Sed:如何封闭匹配的行?
- php - 使用未定义的常量 STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT
- algorithm - 用于子集和问题的多项式\伪多项式算法,具有浮点数和目标和或与目标和最接近的和
- c++ - 如果我将变量重新定义为 auto 并且推导的类型相同,它是否格式正确?
- python - 如何为雅可比矩阵添加停止条件?