Python:我想装饰 MethodType 属性而不将属性类型更改为 FunctionType

标签 python python-2.7 python-decorators

我想实现以下功能而不将 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/

相关文章:

python - Buildbot 不以默认配​​置启动

python - 使用 scipy 进行二维插值/平滑线时如何提高性能?

python-2.7 - 使用数组执行 NDB IN 查询

python - 将列表值与字典匹配并返回新字典中的键/值对

python - 修饰的可调用类上的属性访问

python - 为什么装饰器模块强制我将内部函数提升到外部水平?

python - 使用 pysftp 和 Python 3 仅使用服务器指纹连接到 SFTP 服务器

python - 如何在后台运行python程序?

python - 为什么我们在这个装饰器中返回 None ?

python - 使用 Tilestache 时未定义全局名称 'mapnik'