我有一个简单的问题:为什么在静态方法上使用 staticmethod 装饰器?您可以创建没有“self”参数的静态方法,无需此装饰器。
当使用python2时,这是必要的:
>>> class A:
... def p(object_to_print):
... print(object_to_print)
...
>>> A.p('test')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unbound method p() must be called with A instance as first argument (got str instance instead)
但是,如果我使用 python 3 做同样的事情,它会工作得很好。
如果没有装饰器也能正常工作,为什么还要使用装饰器呢?如果第一个参数不是 self,很明显它是一个静态方法。我能看到的唯一原因是在误用的情况下获得更清晰的错误......
Python 3 中出现这种行为有什么原因吗?
谢谢:) 帕尔克奥。
最佳答案
尝试使用 A
实例调用此方法,您将得到一个异常:
>>> a = A()
>>> a.p('test')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: p() takes 1 positional argument but 2 were given
因为参数被视为实例本身:
>>> a.p()
<__main__.A object at 0x7f9f60f56048>
但是,如果该方法用 staticmethod
修饰,它将按预期工作:
>>> A.p('test')
test
>>> a.p('test')
test
关于python - python3中@staticmethod的好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30461580/