gpt4 book ai didi

Python - 调用覆盖方法时发生 TypeError

转载 作者:太空宇宙 更新时间:2023-11-03 12:51:07 25 4
gpt4 key购买 nike

我遇到了方法覆盖问题。

看下面的src代码,

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)

有趣的是,Foo.bar.im_func 属性实际上是方法并且在调用时工作得很好。我想知道是否有办法使用其 im_func 属性恢复 Foo.bar 方法?请多多指教~

谢谢!

最佳答案

如果你希望它继续是一个静态方法,那么你必须在分配时告诉 Python。否则它将成为一个正常的方法。

Foo.bar = staticmethod(backup)

关于Python - 调用覆盖方法时发生 TypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7200057/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com