0

如何在 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')
4

2 回答 2

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
于 2013-09-19T11:37:31.420 回答
0

技术上正确的答案:

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

但是当一个普通函数可以做时,让它成为一个静态方法有什么意义呢?

于 2013-09-19T11:33:23.147 回答