python - 发送一个 python 修饰方法作为函数参数

标签 python decorator

我目前有以下使用 python 库的代码:

f = Foo(original_method, parameters)

我想增强original_method,并让装饰器添加几行代码。我们将新的装饰方法称为decorated_method。最后我想要这样的东西:

f = Foo(decorated_method(original_method), parameters)

我的问题是:这可能吗?装饰器会是什么样子? 我必须说我无法扩展original_method,因为它是外部库的一部分。

编辑:original_method 不执行,仅作为参数传递给 Foo。 decorated_method 函数应该做一些日志记录并收集一些调用次数的统计数据。

稍后编辑:下面示例中的代码工作正常。我遇到了一些额外的问题,因为original_method 有一些属性,所以这是最终的代码:

def decorated_method(method):

    def _reporter(*args, **kwargs):
        addmetric('apicall', method.__name__)
        return method(*args, **kwargs)

    _reporter.original_method_attribute = method.original_method_attribute
    return _reporter

最佳答案

你没有提到你想要decorated_method做什么,但这当然是可能的:

def decorated_method(f):
    def _wrapped(*args, **kwargs):
        print "About to call f!"
        ret = f(*args, **kwargs)
        print "Just got finished with f, ret = %r" % (ret,)
        return ret
    return _wrapped

这只是标准的装饰器结构:装饰器是一个接受函数并返回函数的函数。

关于python - 发送一个 python 修饰方法作为函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11431207/

相关文章:

python - 从 2 个单独的列表中提取信息

python - pySerial:刷新 vs reset_input_buffer + reset_output_buffer

Python MySQLdb 执行表变量

python - 字符串到 MySQL 中的 DATETIME

c# - 扩展方法 - 装饰者模式

typescript - 是否可以在 Typescript 中装饰装饰器?

python - 如何测试 Python 函数装饰器?

python - 如何使用来自另一个 DataFrame 对象的数据创建 Pandas DataFrame 对象?

python - Ruby 中的函数装饰器,与 Python 中一样

python - 如何使用类实例变量作为 Python 中方法装饰器的参数?