Skip to main content
 首页 » 编程设计

python之numpy 子类将不接受来自 python 继承类的 __new__ 参数

2025年05月04日8bluestorm

我创建了一个名为“Parray”的 ndarray 子类,它有两个参数:p 和维度。它本身工作正常。现在,我想创建一个名为 SirPlotsAlot 的类,它继承了 Parray 而没有所有花哨的 new 和 array_finalize 等。

import numpy as np 
 
class Parray(np.ndarray): 
    def __new__(self, p = Parameters(), dimensionality = 2): 
 
        print "Initializing Parray with initial dimensionality %s..." % dimensionality 
 
        self.p = p # store the parameters 
 
        if dimensionality == 2: 
            shape = (p.nx, p.ny) 
            self.pshape = shape 
        elif dimensionality == 3: 
            shape=(p.nx, p.ny, p.nx) 
            self.pshape = shape 
        else: 
            raise NotImplementedError, "dimensionality must be 2 or 3" 
 
        # ...Set other variables (ellided) 
 
        subarr = np.ndarray.__new__(self, shape, dtype, buffer, offset, strides, order) 
        subarr[::] = np.zeros(self.pshape) # initialize to zero 
        return subarr 
... 
 
class SirPlotsAlot(Parray): 
    def __init__(self, p = Parameters(), dimensions = 3): 
        super(SirPlotsAlot, self).__new__(p, dimensions)     # (1) 

我程序中的对象通过来回传递对象 p = Parameters() 来共享参数集。

现在,当我输入时(文件是 auxiliary.py):

import auxiliary 
from parameters import Parameters 
p = Parameters() 
s = auxiliary.SirPlotsAlot(p, 3) 

期望得到一个很好的“初始化 Parray 的初始维度 3”,但我得到了“2”。但是如果我输入:

import auxiliary 
s = auxiliary.SirPlotsAlot() 

我明白了

---> 67             shape = (p.nx, p.ny) 
"AttributeError: 'int' object has no attribute 'nx'" 

它认为“p”是一个整数,但它不是。如果我玩弄它,我会得到很多看似无关的奇怪错误。它认为它是“2”的整数。我完全迷路了。

我试过使用和不使用 # (1) 注释( super 调用)。

其他错误包括“AttributeError: 'list' object has no attribute 'p'”, “TypeError: new() takes exactly 2 arguments (1 given)”, “ValueError:需要超过 0 个值才能解包”(我用 *args 替换了 new 的参数,这是我不太了解的东西)。

请您参考如下方法:

我要回应 kindall,并说“不要使用 __new__”。您的 Parray.__new__ 方法看起来更像是一个初始化,应该使用 __init__,就像它的子类一样。