Использование np.isrealobj??
в IPython (или ссылка [source]
онлайн):
def isrealobj(x):
"""
Return True if x is a not complex type or an array of complex numbers.
...
See Also
--------
iscomplexobj, isreal
...
"""
return not iscomplexobj(x)
Эта первая строка представляет собой разумное резюме кода, особенно если вы не слишком много читаете в него. Примечание See Also
также указывает в этом направлении. И это, и iscomplexobj
говорят, что они проверяют type
, а не value
со специальным примечанием о an imaginary part equal to zero
.
Код для iscomplexobj
:
try:
dtype = x.dtype
type_ = dtype.type
except AttributeError:
type_ = asarray(x).dtype.type
return issubclass(type_, _nx.complexfloating)
Проверяется dtype
из x
или dtype
np.asarray(x)
, если x
уже не является ndarray
.
In [113]: np.array('1+1j').dtype
Out[113]: dtype('<U4')
In [114]: np.array({}).dtype
Out[114]: dtype('O')
In [115]: np.array(1.23).dtype
Out[115]: dtype('float64')
In [116]: np.array(1.23+0j).dtype
Out[116]: dtype('complex128')
isinstance
проверяет __mro__
стек
In [117]: np.float64.__mro__
Out[117]:
(numpy.float64,
numpy.floating,
numpy.inexact,
numpy.number,
numpy.generic,
float,
object)
In [118]: np.complex128.__mro__
Out[118]:
(numpy.complex128,
numpy.complexfloating,
numpy.inexact,
numpy.number,
numpy.generic,
complex,
object)
Эта логика применяется ко всем перечисленным здесь функциям is_type
:
https://docs.scipy.org/doc/numpy-1.15.1/reference/routines.logic.html#array-type-testing
При понимании функции Python код является королем. Документация должна быть хорошим резюме этого действия, но обычно не может охватить все нюансы. Название в лучшем случае полезно мнемоника. Все они должны быть поняты в контексте Python и их пакета.
Проверка на function
с атрибутом __call__
имеет смысл, как и isinstance
для str
.
real objects
все еще немного неясно. Я думаю, type(12)
и type(12.3)
должны проверить истину. Как насчет type(12+1j)
? Как насчет numpy
массивов или объектов numpy.ScalarType
?
Краткий веб-поиск "python test for number" привел меня к numbers.Number
test:
https://docs.python.org/3.7/library/numbers.html
In [134]: import numbers
In [135]: isinstance(12, numbers.Number)
Out[135]: True
In [136]: isinstance(12.23, numbers.Number)
Out[136]: True
In [137]: isinstance(12.23+1j, numbers.Number)
Out[137]: True
In [138]: isinstance('12.23+1j', numbers.Number)
Out[138]: False
In [139]: isinstance({}, numbers.Number)
Out[139]: False
In [140]: isinstance(np.float64(12), numbers.Number)
Out[140]: True
In [141]: isinstance(np.complex(12), numbers.Number)
Out[141]: True