Why use staticmethod instead of no decorator at all

徘徊边缘 提交于 2021-02-19 04:34:04

问题


There are several good explanations on SO about why/when you should use a class method vs a static method, but I've not been able to find an answer for when you would use a static method over no decoration at all. Consider this

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))

And some output:

>>> 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

From what I've read on here, the primary reason for using staticmethod is basically to keep conceptually similar things together. From the example above, it seems like both solutions do that. The only drawback is that you don't appear to be able to call the non-staticmethod from an instance. Maybe I'm too used to other programming languages, but this does not bother me so much; it's always surprising that I can call class-level stuff from am instance in Python.

So, is this basically the only difference between the two? Or am I missing other benefits? Thanks


回答1:


You seem to be using python 3. In 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)

In python 3, you missed another strange use case:

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'


来源:https://stackoverflow.com/questions/15317478/why-use-staticmethod-instead-of-no-decorator-at-all

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!