Why use staticmethod instead of no decorator at all
关于为什么/什么时候应该使用类方法和静态方法,有好几种很好的解释,但是我还没有找到一个答案,关于什么时候使用静态方法而不使用任何装饰。考虑这个
1 2 3 4 5 6 7 | 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)) |
一些输出:
1 2 3 4 5 6 7 8 9 10 11 12 | >>> 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中的AM实例调用类级的东西。
所以,这基本上是两者之间唯一的区别吗?还是我错过了其他福利?谢谢
您似乎在使用python 3。在Python 2中:
1 2 3 4 5 6 7 8 9 10 11 12 | 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) |
在Python3中,您错过了另一个奇怪的用例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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' |