python中isinstance函数判断各种类型的小细节

1. 基本语法

isinstance(object, classinfo)

Return true if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) 
subclass thereof. Also return true if classinfo is a type object (new-style class) and object is an object of that 
type or of a (direct, indirect or virtual) subclass thereof. If object is not a class instance or an object of the
 given type, the function always returns false. If classinfo is neither a class object nor a type object, it may be a 
 tuple of class or type objects, or may recursively contain other such tuples (other sequence types are not accepted). 
 If classinfo is not a class, type, or tuple of classes, types, and such tuples, a TypeError exception is raised.

classinfo 处可以是 a class, type, or tuple of classes and types,

如果是 tuple,则满足 tuple 中的任何一个即返回 True

2. 字符串的类型判断。

字符串,分为 str 和 unicode,二者均继承自 basestring

>>> isinstance(u'3.0', unicode)
True
>>> isinstance('3.0', str)
True
>>> isinstance(u'3.0', str)
False
>>> isinstance(u'3.0', str)
False
>>> isinstance(u'3.0', basestring)
True
>>> isinstance('3.0', basestring)
True

3. 数字的类型判断

数字分为 int 和 float,暂未发现二者共同的有效父类。

可以用 (int, float) tuple 来判断是否为数字(int 或 float)

>>> isinstance('3', (int, float))
False
>>> isinstance(3.0, (int, float))
True
>>> isinstance(3, (int, float))
True
>>> isinstance(3.0, float)
True
>>> isinstance(3.0, int)
False
>>> isinstance(3, float)
False
>>> isinstance(3, int)
True
  • 17
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hakesashou

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值