How to identify numpy types in python?

前端 未结 6 759
生来不讨喜
生来不讨喜 2020-12-23 09:02

How can one reliably determine if an object has a numpy type?

I realize that this question goes against the philosophy of duck typing, but idea is to make sure a fun

6条回答
  •  独厮守ぢ
    2020-12-23 09:33

    To get the type, use the builtin type function. With the in operator, you can test if the type is a numpy type by checking if it contains the string numpy;

    In [1]: import numpy as np
    
    In [2]: a = np.array([1, 2, 3])
    
    In [3]: type(a)
    Out[3]: 
    
    In [4]: 'numpy' in str(type(a))
    Out[4]: True
    

    (This example was run in IPython, by the way. Very handy for interactive use and quick tests.)

提交回复
热议问题