以下是 的getattribute
方法recarray
。Python 转换obj.par1
为obj.__getattribute__('par1')
. 这可以解释为什么在重新数组中使用时,字段名称必须是有效的属性名称。
def __getattribute__(self, attr):
try:
return object.__getattribute__(self, attr) #**
except AttributeError: # attr must be a fieldname
pass
fielddict = ndarray.__getattribute__(self, 'dtype').fields
try:
res = fielddict[attr][:2]
except (TypeError, KeyError):
raise AttributeError("record array has no attribute %s" % attr)
obj = self.getfield(*res)
# if it has fields return a recarray, otherwise return
# normal array
if obj.dtype.fields:
return obj
if obj.dtype.char in 'SU':
return obj.view(chararray)
return obj.view(ndarray)
该**
行解释了为什么obj.data
返回缓冲区指针,而不是您的字段。同样适用于“形状”和“步幅”。这也使得访问数组方法成为可能。您希望重新排列的行为尽可能像常规数组,不是吗?
结构化数组中的字段名称就像字典的键,形式相对自由(尽管我从未探索过限制)。但是在 中recarray
,这些名称还必须具有属性名称。属性名称必须是有效的变量名称——这是一个 Python 约束。
在https://stackoverflow.com/a/32540939/901925我从genfromtxt
文档中引用:
具有结构化 dtype 的 Numpy 数组也可以视为 recarray,其中可以像访问属性一样访问字段。出于这个原因,我们可能需要确保字段名称不包含任何空格或无效字符,或者它不对应于标准属性的名称(如大小或形状),这会使解释器感到困惑。
还有一个关于 Python 类的教程说:
属性引用使用 Python 中所有属性引用的标准语法:obj.name。有效的属性名称是创建类对象时类名称空间中的所有名称。
https://docs.python.org/2/tutorial/classes.html#tut-object