我尝试定义一个类装饰器。我在被装饰的类中遇到了一个问题,即如果该类的
代码示例:
__init__
方法调用了super
方法,则会引发RuntimeError
maximum recursion depth exceeded错误。代码示例:
def decorate(cls):
class NewClass(cls): pass
return NewClass
@decorate
class Foo(object):
def __init__(self, *args, **kwargs):
super(Foo, self).__init__(*args, **kwargs)
我做错了什么?
谢谢,Michał
编辑1
感谢Mike Boers的回答,我意识到正确的问题是我应该怎么做才能让super(Foo, self)指向正确的类。
我还有两个限制。我想调用Foo.__init__
方法,而且我不能更改Foo
类的定义。
编辑2
我已经解决了这个问题。我修改了装饰器函数体。我不返回新类,而是包装原始类的方法。