簡體   English   中英

從類實例中訪問靜態方法的正確/首選方法

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM