用另一个实例的方法装饰实例的方法

2024-05-16 01:03:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python相当陌生。 我有两个类,每个类有一个实例。 我想用另一个实例的方法装饰其中一个实例的方法,例如:

import functools

class DecoClass():
    def __init__(self, deco_arg):
        self.deco_arg = deco_arg

    def my_decorator(self, f):
        @functools.wraps(f)
        def deco_wrapper(*args):
            print ('deco_wrapper argument :', self.deco_arg) # or just do something with deco_arg
            f = f(*args)
            return f
        return deco_wrapper

###

class MyClass():
    def __init__(self, arg, decorator):
            self.arg = arg
            self.decorator = decorator

    @self.decorator.my_decorator            # this is my problem, how can I do this ?
    def my_function(self):
        print ('my_function : ', self.arg)

###

if __name__ == "__main__":
a = DecoClass(1)
b = MyClass(10, a)
b.my_function()

当然,上述方法不起作用,因为MyClass不知道self.decorator属性(在类级别)。这是可以做到的还是有别的办法

上面的例子过于简单化了。在我的例子中,DecoClass()实际上将负责异常捕获、错误日志(到文件和/或mysql)和其他各种事情。我只想实例化它一次,这样每次使用它时就不必传递参数(logger、db auth等)。另外,DecoClass()将驻留在一个模块中,该模块将由不同的python程序同时使用(每个实例都有自己的参数)

谢谢你抽出时间


Tags: 实例方法selfinitmydefmyclassarg
1条回答
网友
1楼 · 发布于 2024-05-16 01:03:50

这可能无法满足您的需要,但您可以尝试以下方法:

import functools

class DecoClass():
    def __init__(self, deco_arg):
        self.deco_arg = deco_arg

    def my_decorator(self, f):
        @functools.wraps(f)
        def deco_wrapper(*args):
            print ('deco_wrapper argument :', self.deco_arg)
            r = f(*args)
            return r
        return deco_wrapper

###

a = DecoClass(1)
decorator = a.my_decorator

class MyClass():
    def __init__(self, arg):
            self.arg = arg
            self.decorator = decorator

    @decorator
    def my_function(self):
        print ('my_function : ', self.arg)

###

if __name__ == "__main__":
    b = MyClass(10)
    b.my_function()

相关问题 更多 >