使用类对象中的方法装饰python函数

时间:2016-10-31 18:09:02

标签: python class decorator

我想在函数上使用装饰器。事情是装饰器函数是在类中定义的,它必须特定于该类的对象。例如:

class Foo:
    def __init__(self):
        self.a = 1

    def set_a(self, val):
        self.a = val

    def bar(func):
        def _args(*args, **kwargs):
            func(*args, **kwargs) + self.a
        return _args

if __name__ == "__main__":

    foo = Foo()
    foo2 = Foo()

    foo.set_a = 2

    @foo.bar
    def multip(a, b):
        return a * b

    multip(1, 2)  # here i would expect answer to be 4        

    foo.set_a = 3

    multip(1, 2)  # here i would expect answer to be 5

    @foo2.bar
    def multip2(a, b):
        return a * b

    multip2(1, 2)  # here i would expect the answer to be 3

1 个答案:

答案 0 :(得分:0)

所以你可以做你想要的,但我不确定我会认为这是一个好装饰。为什么不去找一个班级装饰者并使用__init__()__call__()

无论如何,这是您的固定代码:

class Foo:
    def __init__(self, a=1):
        self.a = a

    def bar(self, func):
#           ^^^^ you need self
        def _args(*args, **kwargs):
            return func(*args, **kwargs) + self.a
#           ^^^^^^ You need to return here.
    return _args

foo = Foo()

@foo.bar
def multip(a, b):
    return a * b

multip(1, 2)
# 3
foo.a = 2
multip(1, 2)
# 4
foo.a = 3
multip(1, 2)
# 5