我正在尝试“包装”现有的类方法,即
def Foo:
@classmethod
def bar(cls, x): return x + 2
old_bar = Foo.bar
def wrapped_bar(cls, x):
result = old_bar(cls, x) # Results in an error
return result
Foo.bar = wrapped_bar
Foo.bar
似乎已经与 cls = Foo
绑定(bind),如何获取函数 bar
的未绑定(bind)版本?
[我不允许修改 Foo
,它存在于我正在修补的另一个代码库中]
最佳答案
假设,你有:
>>> class Foo:
... @classmethod
... def bar(cls, x):
... return x*42
...
>>> Foo.bar(2)
84
然后一种方法是直接访问类的 namespace 。然后您应该能够访问 classmethod
对象并获得在 __func__
属性中可用的修饰函数:
>>> vars(Foo)['bar']
<classmethod object at 0x103eec520>
>>> vars(Foo)['bar'].__func__
<function Foo.bar at 0x1043e49d0>
或者,它可以在绑定(bind)方法对象本身上访问:
>>> bound = Foo.bar
>>> bound
<bound method Foo.bar of <class '__main__.Foo'>>
>>> bound.__func__
<function Foo.bar at 0x1043e49d0>
关于python - 如何获得无限类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60533691/