编程语言
首页 > 编程语言> > 具有参数的Python类修饰器,但未运行修饰的函数

具有参数的Python类修饰器,但未运行修饰的函数

作者:互联网

我已经大部分工作了.我想要一个类装饰器(Decorator类),该装饰器接受可用于将方法包装在对象(Person的实例)上的参数(问候和告别).

一切正常,除了…永远不会运行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!

解决方法:

您从未调用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!

标签:python-decorators,python
来源: https://codeday.me/bug/20191029/1964027.html