栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何正确使用python的isinstance()检查变量是否为数字?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何正确使用python的isinstance()检查变量是否为数字?

在Python 2中,您可以使用

types
模块:

>>> import types>>> var = 1>>> NumberTypes = (types.IntType, types.LongType, types.FloatType, types.ComplexType)>>> isinstance(var, NumberTypes)True

请注意使用元组来测试多种类型。

在幕后,

IntType
只是的别名
int
,等等:

>>> isinstance(var, (int, long, float, complex))True

complex
类型要求您的python编译时支持复数;如果要对此进行保护,请使用try / except块:

>>> try:...     NumberTypes = (types.IntType, types.LongType, types.FloatType, types.ComplexType)... except AttributeError:...     # No support for complex numbers compiled...     NumberTypes = (types.IntType, types.LongType, types.FloatType)...

或者,如果您直接使用类型:

>>> try:...     NumberTypes = (int, long, float, complex)... except NameError:...     # No support for complex numbers compiled...     NumberTypes = (int, long, float)...

在Python 3中

types
不再具有任何标准类型别名,
complex
始终启用,并且不再存在
long
vs
int
差异,因此在Python
3中始终使用:

NumberTypes = (int, float, complex)

最后但并非最不重要的一点是,您可以使用

numbers.Numbers
抽象基类型(Python
2.6中的新增功能)还支持不直接从上述类型派生的自定义数字类型:

>>> import numbers>>> isinstance(var, numbers.Number)True

此检查也返回

True
decimal.Decimal()
fractions.Fraction()
对象。

该模块确实假定

complex
已启用该类型。如果不是,则会出现导入错误。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/641294.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号