Well, it is expected that the new object will be empty until __init__
called. Probably, python, as an optimization, does not bother to search for an object and is sent to choose __init__
directly from the class.
Therefore, you will have to change the __init__
the subclasses themselves. Fortunately, Python has a tool for this, metaclasses.
In Python 2, you set up a metaclass by setting a special member:
class Parent(object): __metaclass__ = Meta ...
See Python2 Documentation
In Python 3, you set the metaclass through the keyword attribute in the parent list, so
class Parent(metaclass=Meta): ...
See Python3 Documentation
The metaclass is the base class for an instance of the class. It must be obtained from type
and in it __new__
it can change the created class (I believe that the call __init__
should be called, but the examples override __new__
, so I will go with it), __new__
will look like what you have:
class Meta(type): def __new__(mcs, name, bases, namespace, **kwargs): new_cls = super(Meta, mcs).__new__(mcs, name, bases, namespace, **kwargs) user_init = new_cls.__init__ def __init__(self, *args, **kwargs): print("New __init__ called") user_init(self, *args, **kwargs) self.extra() print("Replacing __init__") setattr(new_cls, '__init__', __init__) return new_cls
(using the Python 3 example, but the signature in Python 2 seems the same, but not **kwargs
, but adding them should not hurt, I have not tested it).