I’m running into a problem with method overwriting.
Look at the src code below,
class Foo(object):
@staticmethod
def bar():
pass
Foo.bar() # works fine
print Foo.bar # <function bar at 0x028A5B30>
print dir(Foo.bar)
"""
['__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__',
'__dict__', '__doc__', '__format__', '__get__', '__getattribute__', '__globals__',
'__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__',
'__subclasshook__', 'func_closure', 'func_code', 'func_defaults', 'func_dict',
'func_doc', 'func_globals', 'func_name']
"""
backup = Foo.bar # keep the instance of the method object
Foo.bar = backup # overwrite with the same method object
print Foo.bar # <unbound method Foo.bar>
print dir(Foo.bar)
"""
['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__format__',
'__func__', '__get__', '__getattribute__', '__hash__', '__init__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__',
'__str__', '__subclasshook__', 'im_class', 'im_func', 'im_self']
"""
Foo.bar() # TypeError: unbound method foo() must be called with Test instance as first argument (got nothing instead)
It is interesting that the Foo.bar.im_func attribute is actually the method and works just fine when invoked. I’m wondering if there’s a way to recover the Foo.bar method with its im_func attribute? Please advice~
Thanks!
If you want it to continue to be a static method then you must tell Python so when assigning. Otherwise it will become a normal method.