在Python中继承装饰函数?

时间:2013-09-19 11:21:37

标签: python inheritance static-methods instantiation python-decorators

如何在Python中使用继承的装饰器?

class Foo:
    @staticmethod
    def keyErrorOnRed(f, colour):
        if colour == "red":
            raise KeyError("Better dead than red")
        return lambda: f(*args, **kwargs)

class Bar(Foo):
    @keyErrorOnRed("red")
    def __init__(self, a, b):
        self.vars = a, b

if __name__ == '__main__':
    barObj = Bar('can', 'haz')

2 个答案:

答案 0 :(得分:1)

def keyErrorOnRed(colour):
    def decorate(f):
        def wrapped(*args, **kwargs):
            if colour == "red":
                raise KeyError("Better dead than red")
            return f(*args, **kwargs)
        return wrapped
    return decorate

class Bar(object):
    @keyErrorOnRed("black")  #keyErrorOnRed("black")(Bar.__init__)(self, a, b)
    def __init__(self, a, b):
        self.vars = a, b

答案 1 :(得分:0)

技术上正确的答案:

class Bar(Foo):
    @Foo.KeyErrorOnRed
    def __init__(self, a, b):
        self.vars = a, b

但是当一个简单的函数可以做什么时,将它作为一个静态方法是什么意思呢?