numpy子类将不接受pythonical继承类中的\uunew_uu的参数

2024-09-30 16:34:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经创建了一个名为“Parray”的ndarray子类,它有两个参数:p和维数。它自己工作得很好。现在,我想创建一个名为SirPlotsAlot的类,它继承了Parray而不需要任何花哨的newarray\u 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()来共享参数集。在

现在,当我输入(文件是辅助.py)公司名称:

^{pr2}$

期望得到一个很好的“初始化初始维度为3的粒子阵列”,我得到了“2”。但如果我键入:

import auxiliary
s = auxiliary.SirPlotsAlot()

我明白了

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

它认为“p”是一个int,但它不是。我可以得到许多奇怪的似乎无关的错误,如果我玩它。它认为它是“2”。我完全迷路了。在

我试过使用和不使用#(1)注释(超级呼叫)。在

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


Tags: importselfnew参数npclassndarraynx
1条回答
网友
1楼 · 发布于 2024-09-30 16:34:10

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

相关问题 更多 >