装饰器和带参数的继承

时间:2018-04-08 01:55:11

标签: python inheritance parameters decorator

有一个带继承的装饰器。效果很好:

class bar(object):
    def __init__(self,val):
        self.val = val

    @staticmethod
    def decor(func):
        def increment(obj, x):
            return func(obj, x) + obj.val
        return increment

class foo(bar):
    def __init__(self):
        bar.__init__(self)

    @bar.decor
    def add(self, x):
        return x

但我想在class foo中添加一个参数:

class foo(bar):
    def __init__(self,B):
        bar.__init__(self)
        self.B = B

我想将B作为参数输入到装饰器中,我尝试了划痕:

class bar(object):
    def __init__(self,val):
        self.val = val

    @staticmethod
    def decor(B):
        def wrap(func):
            def increment(obj, x):
                return func(obj, x) + obj.val + B
            return increment
        return wrap

class foo(bar):
    def __init__(self,B):
        bar.__init__(self)
        self.B = B

    @bar.decor(B)
    def add(self, x):
        return x

但它没有用。我做错了什么?

1 个答案:

答案 0 :(得分:0)

class bar(object):
    def __init__(self, val):
        self.val = val

    @staticmethod
    def decor(func):
        def increment(obj, x):
            return func(obj, x) + obj.val + obj.B
        return increment

class foo(bar):
    def __init__(self,val,B):
        bar.__init__(self,val)
        self.B = B

    @bar.decor
    def add(self, x):
        return x

aa = foo(4, 1.5)
a = aa.add(1)
print(a)