繁体   English   中英

创建numpy自定义对象数组会出现错误“SystemError:error return return without exception set”

[英]Creating numpy array of custom objects gives error “SystemError: error return without exception set”

我正在尝试使用numpy来存储我制作的一些自定义对象。 以下是我的程序的简化版本

import numpy as np

class Element:
    def __init__(self): pass

a = Element()
periodicTable = np.array(range(7*32)).reshape((7,32))
periodicTable[0][0] = a

但是,当我运行这个时,我得到了

Traceback (most recent call last):
  File "C:/Users/Dan/Desktop/a.py", line 9, in <module>
    periodicTable[0][0] = a
SystemError: error return without exception set

我不确定我做错了什么 - 据我所知,我所做的一切都应该是合法的。 隐秘的错误信息本身并不是很有帮助 - 我认为这是一个numpy问题,但我一直无法确定我的问题。

@ user2357112确定了问题:您正在将一个Element实例分配给一个包含整数的numpy数组。 这是我尝试类似的东西时得到的:

>>> import numpy as np
>>> np.__version__
'1.7.1'
>>> p = np.array([1,2,3])
>>> class Foo:
...     pass
... 
>>> p[0] = Foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
SystemError: error return without exception set
>>> 

毫不奇怪,这是不允许的。 然而,这个神秘的错误消息几乎肯定是一个笨拙的错误。

解决此问题的一种方法是使用类型为object的数组。 改变这一行:

    periodicTable = np.array(range(7*32)).reshape((7,32))

对此:

    periodicTable = np.empty((7,32), dtype=object)

更新

在numpy 1.10.1中,错误消息仍然有点神秘:

>>> import numpy as np
>>> np.__version__
'1.10.1'    
>>> p = np.array([1, 2, 3])
>>> class Foo:
...     pass
...  
>>> p[0] = Foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: Foo instance has no attribute '__trunc__'

更新2

numpy的更高版本的错误消息更好:

In [1]: import numpy as np

In [2]: np.__version__
Out[2]: '1.12.1'

In [3]: class Foo:
   ...:     pass
   ...: 

In [4]: p = np.array([1, 2, 3])

In [5]: p[0] = Foo()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-739d5e5f795b> in <module>()
----> 1 p[0] = Foo()

TypeError: int() argument must be a string, a bytes-like object or a number, not 'Foo'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM