python - python3中@staticmethod的好处?

标签 python python-3.x static-methods

我有一个简单的问题:为什么在静态方法上使用 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/

相关文章:

Python 分区依据

python - 在 python 3 中查找字符串中的重复项

c++ - 如何实现静态虚成员函数

java无法从同一个类中获取静态变量的值

python - Dockerfile RUN 命令返回 "No such file or directory"

python - 使用 Tkinter 在未知长度的可迭代中为每个项目创建一个条目

python - 卸载包时如何自动删除pipenv中的依赖Python包?

c# - 无法在静态方法中调用 Response.Redirect

python - TypeError : must be string or buffer, not int:执行 sqlAlchemy 查询时

python - Scrapy-splash response.css() 获取不到元素