gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 22:38:18 24 4
gpt4 key购买 nike

我想在不将 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/

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