Superior Python class decorator and maximum recursion depth

I am trying to define a decorator class. I have a problem with a method __init__in a decorated class. If the method __init__calls super, the maximum recursion depth is exceeded RuntimeError.

Code example:

def decorate(cls):
    class NewClass(cls): pass
    return NewClass

@decorate
class Foo(object):
    def __init__(self, *args, **kwargs):
        super(Foo, self).__init__(*args, **kwargs)

What am I doing wrong?

Thanks Michaล‚

Change 1

Thanks to Mike Boer's answer, I realized that the right question is what I have to do to ensure that super (Foo, self) points to the corresponding class.

I also have two limitations. I want to call the method Foo.__init__, and I can not change the class definition Foo.

Edit 2

I solved this problem. I am changing the body of the decorator function. I am not returning a new class. Instead of wrapping the methods of the original class.

+3
2

NewClass.__init__, , NewClass.__init__ - Foo.__init__, .

def decorate(cls):
    class NewClass(cls):
        def __init__(self):
            pass
    return NewClass

:

, ? , - - ?

def decorate(cls):
    old_do_something = cls.do_something
    def new_do_something(self):
        print "decorated",
        old_do_something(self)

    cls.do_something = new_do_something
    return cls

@decorate
class Foo(object):
    def __init__(self, *args, **kwargs):
        super(Foo, self).__init__(*args, **kwargs)

    def do_something(self):
        print "Foo"

f = Foo()
f.do_something()
+4

, - :

>>> Foo = decorate(Foo)

, Foo NewClass. Foo.__init__ __init__ of NewClass, Foo.__init__ ( , ).

, Foo.__init__ __init__ , .

+3

Source: https://habr.com/ru/post/1749199/


All Articles