I'm interested in using the __new__
functionality to inject code into the __init__
function of subclasses. My understanding from the documentation is that python will call __init__
on the instance returned by __new__
. However, my efforts to change the value of __init__
in the instance before returning it from __new__
don't seem to work.
class Parent(object):
def __new__(cls, *args, **kwargs):
new_object = super(Parent, cls).__new__(cls)
user_init = new_object.__init__
def __init__(self, *args, **kwargs):
print("New __init__ called")
user_init(self, *args, **kwargs)
self.extra()
print("Replacing __init__")
setattr(new_object, '__init__', __init__)
return new_object
def extra(self):
print("Extra called")
class Child(Parent):
def __init__(self):
print("Original __init__ called")
super(Child, self).__init__()
c = Child()
The above code prints:
Replacing __init__
Original __init__ called
but I would expect it to print
Replacing __init__
New __init__ called
Original __init__ called
Extra called
Why not?
I feel like Python is calling the original value of __init__
, regardless of what I set it to in __new__
. Running introspection on c.__init__
shows that the new version is in place, but it hasn't been called as part of the object creation.