带参数的装饰器和继承

2024-06-16 10:55:41 发布

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

有个装饰师继承了遗产。效果很好:

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作为参数输入到decorator中,我尝试了一个scratch:

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

但没用。我做错什么了?你知道吗


Tags: selfaddobjreturnobjectfooinitdef
1条回答
网友
1楼 · 发布于 2024-06-16 10:55:41
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)

相关问题 更多 >