Python @staticmethod装饰器做什么了吗?
我上了两门课:Python @staticmethod装饰器做什么了吗?,python,python-3.x,Python,Python 3.x,我上了两门课: class A: @staticmethod def f(x): print("x is", x) class B: def f(x): print("x is", x) 然后像这样使用它们: >>> A.f(1) x is 1 >>> B.f(1) x is 1 看起来f甚至在没有decorator的情况下也变成了B上的静态方法。为什么我需要decorator?在Python2中,
class A:
@staticmethod
def f(x):
print("x is", x)
class B:
def f(x):
print("x is", x)
然后像这样使用它们:
>>> A.f(1)
x is 1
>>> B.f(1)
x is 1
看起来
f
甚至在没有decorator的情况下也变成了B上的静态方法。为什么我需要decorator?在Python2中,decorator的重要性更大,在Python2中,实例方法的实例性得到了更强烈的强制:
>>> class B:
... def f(x):
... print("x is", x)
...
>>> B.f(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unbound method f() must be called with B instance as first argument (
got int instance instead)
>>B类:
... def f(x):
... 打印(“x是”,x)
...
>>>B.f(1)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
TypeError:必须以B实例作为第一个参数调用未绑定的方法f()(
取而代之的是int实例)
那时,您必须使用@staticmethod
标记静态方法
现在,
@staticmethod
仍然清楚地表明该方法是静态的,这有助于代码可读性和文档生成,并且它允许您在实例上调用该方法,而无需系统尝试绑定self
试试这两个类,它们都有cry
方法,一个作为classmethod,另一个作为传递了self
的staticmethod
class Cat:
def __init__(self):
self.sound = "meow"
def cry(self):
print(self.sound)
x = Cat()
x.cry()
meow
还有另一门课
class Dog:
def __init__(self):
self.sound = "ruff-ruff"
@staticmethod
def cry(self):
print(self.sound)
x = Dog()
x.cry()
TypeError: cry() missing 1 required positional argument: 'self'
我们可以看到,
@staticmethod
装饰器基本上删除了传入的self
IMO,staticmethod
提供的实用程序很少。它所做的事情是让您可以从类的实例以及从类调用它。所以试着做B().f(1)
和A().f(1)
。我很确定它只适用于来自Java等语言的人,这些语言迫使你为所有东西编写类定义。我几乎总是使用一个独立的函数,而不是staticmethod