您的位置:首页 > 编程语言 > Python开发

Python 类型比较: type 和 isinstance

2016-12-15 15:23 387 查看

OLD ( 不推荐的方式)

if type(obj) == type(0) …

if type(obj) == types.IntType…

Better:

if type(obj) is type(0) …

Even Better:

if isinstance(obj, int)…

if isinstance(obj, (int, long))…

if type(obj) is int…

注意:

尽管 isinstance() 很灵活,但它没有执行 "严格匹配" 比较, 如果 obj 是一个给定类型的实例或者子类的实例,也会返回 True.
如果想进行严格匹配,仍需要使用 is.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: