Python Decorators and inheritance

前端 未结 1 1451
庸人自扰
庸人自扰 2020-12-25 15:00

Help a guy out. Can\'t seem to get a decorator to work with inheritance. Broke it down to the simplest little example in my scratch workspace. Still can\'t seem to get it

相关标签:
1条回答
  • 2020-12-25 15:27

    Define decor as a static method and use the form @bar.decor:

    class bar(object):
        def __init__(self):
            self.val = 4
        def setVal(self,x):
            self.val = x
        @staticmethod
        def decor(func):
            def increment(self, x):
                return func(self, x) + self.val
            return increment
    
    class foo(bar):
        def __init__(self):
            bar.__init__(self)
        @bar.decor
        def add(self, x):
            return x
    
    0 讨论(0)
提交回复
热议问题