python - 为什么使用 staticmethod 而不是根本不使用装饰器

标签 python oop function static-methods

关于为什么/何时应该使用类方法与静态方法,有几个关于 SO 的很好的解释,但我一直无法找到关于何时使用静态方法而不是根本没有修饰的答案。考虑一下

class Foo(object):        
    @staticmethod
    def f_static(x):
        print("static version of f, x={0}".format(x))

    def f_standalone(x):
        print("standalone verion of f, x={0}".format(x))

还有一些输出:

>>> F = Foo
>>> f = F()
>>> F.f_static(5)
static version of f, x=5
>>> F.f_standalone(5)
standalone verion of f, x=5
>>> f.f_static(5)
static version of f, x=5
>>> f.f_standalone(5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: f_standalone() takes 1 positional argument but 2 were given

从我在这里读到的内容来看,使用 staticmethod 的主要原因基本上是为了将概念上相似的东西放在一起。从上面的例子来看,这两种解决方案似乎都是这样做的。唯一的缺点是您似乎无法从实例调用非静态方法。也许我对其他编程语言太习惯了,但这并没有给我带来太大的困扰;我可以从 Python 中的实例调用类级别的东西总是令人惊讶。

那么,这基本上是两者之间唯一的区别吗?还是我错过了其他福利?谢谢

最佳答案

您似乎使用的是 python 3。在 python 2 中:

In [1]: class Foo(object):
   ...:     def f_standalone(x):
   ...:         print("standalone version of f, x={}".format(x))
   ...:

In [2]: Foo.f_standalone(12)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-2d315c006153> in <module>()
----> 1 Foo.f_standalone(12)

TypeError: unbound method f_standalone() must be called with Foo instance as first argument (got int instance instead)

在 python 3 中,你错过了另一个奇怪的用例:

In [1]: class Foo(object):
   ...:     def f_standalone(x):
   ...:         print("standalone version of f, x={}".format(x))
   ...:     @staticmethod
   ...:     def f_static(x):
   ...:         print("static version of f, x={}".format(x))
   ...:

In [2]: Foo().f_standalone()
standalone version of f, x=<__main__.Foo object at 0x1064daa10>

In [3]: Foo().f_static()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-addf9c3f2477> in <module>()
----> 1 Foo().f_static()

TypeError: f_static() missing 1 required positional argument: 'x'

关于python - 为什么使用 staticmethod 而不是根本不使用装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15317478/

相关文章:

java - 数字系统类的继承层次

javascript - 获取从星期日开始的周数

bash - 如何通过 find -exec 使用 .bashrc 中定义的 bash 函数

python - CM 到 INCH 转换程序 Python

python - retweeters python twitter api实现

oop - 如何将填充结构/表定义为 ABAP 对象中的类常量

javascript - 封装在 Javascript 中

javascript - 具有独特匿名函数的removeEventListener

python - 有没有更好的方法来设计 Message 模型?

Python 正则表达式词距