我想实现以下功能而不将 type(testObject) 更改为 FunctionType:
import functools
class TestClass(object):
def speak(self):
print 'My Name is Test'
def hello_decorator(func):
@functools.wraps(func)
def hello_func(*args , **kwargs):
print 'Hello World'
return func(*args , **kwargs)
return hello_func
testObject = TestClass()
preDecoratedSpeak = hello_decorator(getattr(testObject , 'speak'))
setattr(testObject , 'speak' , preDecoratedSpeak)
testObject.speak()
print type(testObject.speak)
输出:
Hello World
My Name is Test
<type 'function'>
有没有办法在保持方法为 MethodType 实例化的同时装饰方法?
最佳答案
不幸的是,functools.wraps
在 python 2 中存在一些缺点,其中许多缺点在 python3 中已得到修复。
尝试使用wrapt相反:
The wrapt module focuses very much on correctness. It therefore goes way beyond existing mechanisms such as
functools.wraps()
to ensure that decorators preserve introspectability, signatures, type checking abilities etc. The decorators that can be constructed using this module will work in far more scenarios than typical decorators and provide more predictable and consistent behaviour.
关于Python:我想装饰 MethodType 属性而不将属性类型更改为 FunctionType,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35706465/