为什么使用staticmethod而不使用其他装饰器
在StackOverflow上,有很多关于什么时候使用类方法和静态方法的好解释,但我找不到为什么在某些情况下使用静态方法而不使用普通方法的答案。想想这个例子:
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
根据我在这里看到的,使用静态方法的主要原因就是把概念上相似的东西放在一起。从上面的例子来看,这两种解决方案似乎都做到了这一点。唯一的缺点是,你似乎不能通过实例来调用非静态方法。也许我对其他编程语言太习惯了,但这对我来说并不是太大的问题;在Python中,从实例调用类级别的东西总是让我感到惊讶。
那么,这基本上就是两者之间的唯一区别吗?还是我错过了其他好处?谢谢
1 个回答
2
你似乎在使用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'