gpt4 book ai didi

python - 你能在Python中修改包的基类吗?

转载 作者:行者123 更新时间:2023-12-01 05:38:32 24 4
gpt4 key购买 nike

我已经安装了一个 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 语言编写)。

我相信你想要做的是一个巨大的黑客,这只会导致问题,所以我强烈建议你不要替换你所使用的基类的__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'

关于python - 你能在Python中修改包的基类吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18270548/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com