如何在python中识别numpy类型? [英] How to identify numpy types in python?

查看:168
本文介绍了如何在python中识别numpy类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何可靠地确定一个对象是否具有numpy类型?

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

我意识到这个问题与鸭子类型的哲学背道而驰,但是我们的想法是确保一个函数(使用scipy和numpy)永远不会返回一个numpy类型,除非使用numpy类型进行调用. 这出现在另一个问题的解决方案中,但我认为确定对象是否具有numpy类型的一般问题与应将其分开的原始问题相距甚远.

I realize that this question goes against the philosophy of duck typing, but idea is to make sure a function (which uses scipy and numpy) never returns a numpy type unless it is called with a numpy type. This comes up in the solution to another question, but I think the general problem of determining if an object has a numpy type is far enough away from that original question that they should be separated.

推荐答案

使用内置的type函数获取类型,然后可以使用__module__属性来查找其定义位置:

Use the builtin type function to get the type, then you can use the __module__ property to find out where it was defined:

>>> import numpy as np
a = np.array([1, 2, 3])
>>> type(a)
<type 'numpy.ndarray'>
>>> type(a).__module__
'numpy'
>>> type(a).__module__ == np.__name__
True

这篇关于如何在python中识别numpy类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆