当然可以。干脆做BaseClass.__init__ = your_new_init
。BaseClass
但是,如果在其中实现,这将不起作用C
(并且我相信您无法可靠地更改用 C 实现的类的特殊方法;您可以自己用 C 编写)。
我相信你想要做的是一个巨大的黑客,这只会导致问题,所以我强烈建议你不要替换__init__
你甚至没有写的基类。
一个例子:
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'