【发布时间】:2020-09-22 23:55:09
【问题描述】:
在下面的示例中,我创建了一个自定义类型,然后创建了一个此类型元素的数组,然后我使用 isinstance() 针对此类型测试此数组的第一个元素,但我得到了一个错误。
import numpy as np
# Here I define a simple type with two fields
my_type_simple = np.dtype([('field_1', int), ('field_2', float)])
# An array using the above type
my_var_simple_1 = np.array([(1, 1), (2, 2)], dtype=my_type_simple)
# For a check, should print [(1, 1.) (2, 2.)]
print(my_var_simple_1)
# For a check, should print True
print(isinstance(my_var_simple_1, np.ndarray))
# The below prints numpy.void - how can I find out that in fact it is 'my_type_simple' ?
print(type(my_var_simple_1[0]))
# The below prints True, at least
print(isinstance(my_var_simple_1[0], type(my_var_simple_1[0])))
# But the below raises an Error: TypeError: isinstance() arg 2 must be a type or tuple of types
print(isinstance(my_var_simple_1[0], my_type_simple))
因此问题是:我如何测试才能发现my_var_simple_1[0] 的type 实际上是my_simple_type?这可能吗?
【问题讨论】: