类装饰器的方法和函数的装饰器

时间:2021-04-28 08:32:59

标签: python methods decorator callable

假设我有一个装饰器,我想检索可调用对象并将其放置在不同的方法中:

class Decorator:
    def __init__(self, callback):
         self.callback = callback
    
    def execute(self, arg):
        print("Decorating code")
        return self.callback(arg)

class Decorated:
    @Decorator
    def run(self, arg):
        print(arg)
        return arg

@Decorator
def run(arg):
    print(arg)
    return arg

如何编写装饰器,使其能够同时处理函数和方法?我知道我需要让它返回一个函数才能绑定到实例,但我的目标是将它转换为 Decorator 的实例,以便它的 execute 方法可以在接口的不同部分调用代码。

0 个答案:

没有答案