![](/img/trans.png)
[英]how to access a python method within a class from a staticmethod within the same class
[英]Correct/preferred way to access staticmethod from within class instance
從 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
是從Foo
派生的類的實例,則self.div_2
可能會調用不同的方法:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.