[英]numpy subclass will not accept arguments to __new__ from pythonically inheriting class
I've created a subclass of ndarray called "Parray" which takes two arguments: p, and dimensionality. 我创建了一个名为“ Parray”的ndarray子类,该子类带有两个参数:p和维数。 It works fine on its own. 它本身可以正常工作。 Now, I want to create a class called SirPlotsAlot, which inherits Parray without all the fancy new and array_finalize etc. 现在,我想创建一个名为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)
Objects in my program share sets of parameters by passing an object p = Parameters() back and forth. 我的程序中的对象通过前后传递对象p = Parameters()来共享参数集。
Now, when I type (the file is auxiliary.py): 现在,当我键入时(文件为auxiliary.py):
import auxiliary
from parameters import Parameters
p = Parameters()
s = auxiliary.SirPlotsAlot(p, 3)
expecting to get a nice "Initializing Parray with initial dimensionality 3", I get "2", instead. 期望得到一个不错的“初始维数为3的初始化Parray”,我得到的是“ 2”。 BUT if I type: 但是如果我输入:
import auxiliary
s = auxiliary.SirPlotsAlot()
I get 我懂了
---> 67 shape = (p.nx, p.ny)
"AttributeError: 'int' object has no attribute 'nx'"
It thinks "p" is an int, which it is not. 它认为“ p”是一个整数,不是。 I can get lots of weird seemingly unrelated errors if I play around with it. 如果我玩弄它,可能会得到很多看似无关的奇怪错误。 The int it thinks it is is "2". 它认为它是“ 2”的整数。 I'm completely lost. 我完全迷路了。
I've tried with and without the # (1) comment (the super call). 我试过有无#(1)注释(超级调用)。
Other errors from playing around include "AttributeError: 'list' object has no attribute 'p'", "TypeError: new () takes exactly 2 arguments (1 given)", "ValueError: need more than 0 values to unpack" (I replaced new 's arguments with *args, something I don't understand very well). 出现的其他错误包括“ AttributeError:'list'对象没有属性'p'”,“ TypeError: new ()恰好接受2个参数(给定1个)”,“ ValueError:需要多个0值来解压缩”(我用* args替换了new的参数,我对此不太了解)。
I'm going to echo kindall, and say "don't use __new__
". 我将回显kindall,并说“不要使用__new__
”。 Your Parray.__new__
method looks more like an initialisation, and should be using __init__
, like it's subclass is. 您的Parray.__new__
方法看起来更像是一个初始化,并且应该使用__init__
,就像它的子类一样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.