lundi 20 novembre 2017

python decorator that calls super init

I'm trying to make a decorator that automatically calls the parent class init. It works with single inheritance but when I try to chain the effect I get a stack overflow error. Can anyone explain (a) Why this is happening and (b) How to accomplish what I want to accomplish?

def init(__init):
    def wrapper(self, *args, **kwargs):
        self.__class__.__bases__[0].__init__(self)
        __init(self)
    return wrapper

class Base:
    def __init__(self):
        print("base init")


class Parent(Base):
    @init
    def __init__(self):
        print("parent init")

class Child(Parent):
    @init
    def __init__(self):
        print("child init")

a = Parent() #works
#c = Child() #stack overflow





Aucun commentaire:

Enregistrer un commentaire