Why use staticmethod instead of no decorator at all

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


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'
链接地址: http://www.djcxy.com/p/54146.html

上一篇: Python中的@staticmethod有什么意义?

下一篇: 为什么使用staticmethod而不是装饰器?