簡體   English   中英

使用@static方法有什么好處嗎?

[英]Are there any benefits from using a @staticmethod?

我想知道你是否在你的代碼中使用@staticmethod裝飾器。

就個人而言,我不使用它,因為它需要更多的信件來寫@staticmethod然后自己。

使用它的唯一好處(來自我)可能是更好的代碼清晰度,但由於我經常為sphinx編寫方法描述,我總是聲明方法是否使用對象。

或者也許我應該開始使用@staticmethod裝飾器?

是否使用@staticmethod取決於您想要實現的目標。 忽略裝飾器,因為要輸入更多內容是一個相當愚蠢的原因(沒有冒犯!)並且表明你還沒有理解Python中靜態方法的概念!

靜態方法獨立於類和任何類實例。 它們僅將類作用域用作命名空間。 如果省略@staticmethod裝飾器,則創建一個在不構造實例的情況下無法使用的實例方法。

這是一個非常簡單的類Foo

>>> class Foo(object):
...    @staticmethod
...    def foo():
...       print 'foo'
...
...    def bar(self):
...       print 'bar'

現在, Foo.foo()是一個可以直接調用的靜態方法:

>>> Foo.foo()
foo

Foo.bar()是一個實例方法 ,只能從Foo實例(對象)調用:

>>> Foo.bar()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unbound method foo() must be called with Foo instance as first argument (got nothing instead)
>>> foo = Foo()
>>> foo.bar()
bar

要回答您的問題:如果要定義靜態方法,請使用@staticmethod 否則,不要。

如果你有一個不使用self的方法,因此可以寫成靜態方法,那么問問自己:你是否想要從外部訪問這個函數而不需要實例? 大多數時候,答案是:不。

假設我們想在Math類中定義abs方法,那么我們有兩個選擇:

class Math():
    def abs(n):
        if n>0:
            return n
        else:
            return -n

class Math2():
    @staticmethod
    def abs(n):
        if n>0:
            return n
        else:
            return -n

在Python2中:

>>> Math.abs(-2)
TypeError: unbound method abs() must be called with Math instance as 
first argument (got int instance instead)

>>>Math().abs(-2)
TypeError: abs() takes exactly 1 argument (2 given)

>>> Math2.abs(-2)
2

>>> Math2().abs(-2)
2

python2自動將Math().abs(-2)作為Math().abs(self,-2) ,因此必須使用@staticmethod

在Python3中

>>>Math.abs(-3)
3

>>>Math().abs(-3)
TypeError: abs() takes 1 positional argument but 2 were given

>>>Math2.abs(-3)
3

>>>Math2().abs(-3)
3

在python3中,您可以使用classname.method()而不使用靜態方法,但是當有人嘗試使用instance.method()時,它會引發TypeError。

除了之前的答案,來自pythons doc @staticmethod:

它可以在類(例如Cf())或實例(例如C()。f())上調用。 除了類之外,該實例被忽略。

class Test:

@staticmethod
def Foo():
    print('static Foo')

def Bar():
    print('static Bar')


Test.foo() # static Foo
Test.bar() # static Bar

obj = Test()
obj.foo() # static Foo ; note that you can call it from class instance 
obj.bar() # ERROR 

@staticmethod裝飾器可以節省您的輸入並提高可讀性。

class Example:
    @staticmethod
    def some_method():
        return

是相同的:

class Example:
    def some_method():
        return
    some_method = staticmethod(some_method)

我想你可能會對Python中的靜態方法感到困惑,因為術語與其他語言不同。 常規方法“綁定”到實例( self ),類方法“綁定”到類( cls ),而靜態方法根本不“綁定”(並且不能訪問實例或類屬性)。

看到:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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