Of course you can. Simply do BaseClass.__init__ = your_new_init
. This does not work if the BaseClass
is implemented in C
however(and I believe you cannot reliably change a special method of a class implemented in C; you could do this writing in C yourself).
I believe what you want to do is a huge hack, that will only cause problems, so I strongly advise you to not replace __init__
of a base class that you didn't even write.
An example:
In [16]: class BaseClass(object):
...: def __init__(self, a, b):
...: self.a = a
...: self.b = b
...:
In [17]: class A(BaseClass): pass
In [18]: class B(BaseClass): pass
In [19]: BaseClass.old_init = BaseClass.__init__ #save old init if you plan to use it
In [21]: def new_init(self, a, b, c):
...: # calling __init__ would cause infinite recursion!
...: BaseClass.old_init(self, a, b)
...: self.c = c
In [22]: BaseClass.__init__ = new_init
In [23]: A(1, 2) # triggers the new BaseClass.__init__ method
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-23-09f95d33d46f> in <module>()
----> 1 A(1, 2)
TypeError: new_init() missing 1 required positional argument: 'c'
In [24]: A(1, 2, 3)
Out[24]: <__main__.A at 0x7fd5f29f0810>
In [25]: import numpy as np
In [26]: np.ndarray.__init__ = lambda self: 1 # doesn't work as expected
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-26-d743f6b514fa> in <module>()
----> 1 np.ndarray.__init__ = lambda self: 1
TypeError: can't set attributes of built-in/extension type 'numpy.ndarray'