【问题标题】:Python class decorators with arguments, but decorated function is not being run带参数的 Python 类装饰器,但未运行装饰函数
【发布时间】:2014-01-24 17:55:22
【问题描述】:

我大部分时间都在工作。我想要一个类装饰器(Decorator 类),它接受可用于在对象(Person 的实例)上包装方法的参数(greetingfarewell)。

一切正常,除了... Person 类上的原始命令函数永远不会运行!如果我使用类似的方法手动调用函数

output = getattr(instance, func.func_name)(command, *args, **kwargs)

我得到了无限递归。

我该怎么做?完整代码如下:

import functools

class Decorator(object):
    def __init__(self, greeting, farewell, *args, **kwargs):
        print "initing"
        self.greeting = greeting
        self.farewell = farewell

    def __call__(self, func, *args, **kwargs):
        print "CALLING"

        @functools.wraps(func)
        def wrapper(instance, command, *args, **kwargs):
            return "%s, %s! %s!\n%s, %s!" % (
                self.greeting,
                instance.name,
                command,
                self.farewell,
                instance.name
            )
        return wrapper

class Person(object):
    def __init__(self, name):
        self.name = name

    @Decorator("Hello", "Goodbye")
    def command(self, data):
        return data + "LIKE A BOSS"

s = Person("Bob")
print s.command("eat food")

实际输出:

initing
CALLING
Hello, Bob! eat food!
Goodbye, Bob!

预期输出:

initing
CALLING
Hello, Bob! eat food LIKE A BOSS!
Goodbye, Bob!

【问题讨论】:

  • 根据您的使用示例,__call__ 只需带一个参数:func

标签: python python-decorators


【解决方案1】:

您从未致电func 来获取原始消息:

def wrapper(instance, command, *args, **kwargs):
            original_value = func(instance, command) #call func here
            return "%s, %s! %s!\n%s, %s!" % (
                self.greeting,
                instance.name,
                original_value,
                self.farewell,
                instance.name
            )

输出:

initing
CALLING
Hello, Bob! eat food LIKE A BOSS!
Goodbye, Bob!

【讨论】:

    【解决方案2】:

    您必须在包装器中的某处调用 func(data) 以获得“LIKE A BOSS”结果并将其添加到预期输出中

    【讨论】:

      猜你喜欢
      • 2014-07-21
      • 2015-10-19
      • 1970-01-01
      • 2014-03-24
      • 1970-01-01
      • 1970-01-01
      • 2011-11-21
      • 2016-09-27
      • 2012-03-14
      相关资源
      最近更新 更多