[英]Can you modify a package's base class in python?
我安裝了一個python軟件包(示意圖),該軟件包具有從基類擴展的許多類。
class BaseType(object):
def __init__(self, required=False, default=None ...)
...
class StringType(BaseType):
...
class IntType(BaseType):
...
我希望能夠修改BaseType類,因此它將接受其他構造函數變量。
我知道我可以基於這些定義自己的類,但是我想知道Python中是否真的有一種方法可以只修改基類?
謝謝你,本
當然可以。 只需執行BaseClass.__init__ = your_new_init
。 但是,如果BaseClass
是用C
實現的,那么這是行不通的(我相信您不能可靠地更改用C實現的類的特殊方法;您可以自己用C編寫此代碼)。
我相信您想要做的是一個巨大的hack,只會造成問題,因此,我強烈建議您不要替換甚至沒有編寫的基類的__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'
您可能可以編輯定義了基類的源文件,或者制作該程序包的副本並編輯特定項目的源代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.