我们真的需要python中的@staticmethod装饰器来声明静态方法

San*_*jay 17 python static

我很好奇为什么我们需要@staticmethod装饰器将方法声明为static.我正在阅读Python中的静态方法,我开始知道静态方法可以在不实例化其类的情况下进行调用.所以我尝试了下面的两个例子,但两者都做了同样的事情:

class StatMethod:
  def stat():
    print("without Decorator")

class StatMethod_with_decorator:
  @staticmethod
  def stat():
    print("With Decorator")
Run Code Online (Sandbox Code Playgroud)

如果我stat()直接在类上调用该方法,则打印/显示以下值:

>> StatMethod.stat()
without Decorator
>> StatMethod_with_decorator.stat()
With Decorator
Run Code Online (Sandbox Code Playgroud)

Cor*_*mer 38

如果您打算尝试直接@staticmethod从类的实例而不是类中调用,则需要装饰器

class Foo():
    def bar(x):
        return x + 5

>>> f = Foo()
>>> f.bar(4)
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    f.bar(4)
TypeError: bar() takes 1 positional argument but 2 were given
Run Code Online (Sandbox Code Playgroud)

现在,如果我宣布@staticmethodself参数不隐式传递作为第一个参数

class Foo():
    @staticmethod
    def bar(x):
        return x + 5

>>> f = Foo()
>>> f.bar(4)
9
Run Code Online (Sandbox Code Playgroud)