Create staticmethod from existing method outside class? ("unrelated method" error)

How can you create a class method static after class definition? In other words, why does the third case fail?

>>> class b:
... @staticmethod
... def foo ():
... pass
...
>>> b.foo ()
>>> class c:
... def foo ():
... pass
... foo = staticmethod (foo)
...
>>> c.foo ()
>>> class d:
... def foo ():
... pass
...
>>> d.foo = staticmethod (d.foo)
>>> d.foo ()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unbound method foo () must be called with d instance as first argument (got nothing instead)
+5
source share
2 answers

foo - unbound method (, ), . (self) , , .

staticmethod() . ( b c), foo() - , , .

unbound method, staticmethod() .

class d(object):
    def foo():
       pass

d.foo = staticmethod(d.foo.im_func)

Python 3 (, , ). , Python 3.

, Python 2, Python 3:

d.foo = staticmethod(d.__dict__['foo'])

( .)

+6

, .

>>> class d:
...   def foo():
...     pass
... 
>>> d.foo = staticmethod(d.foo.im_func)
>>> d.foo()
+5

All Articles