python不使用type(obj) is **来判断变量的类型

来源:互联网 发布:java开发简历项目描述 编辑:程序博客网 时间:2024/06/04 20:03

有时我想判断一个变量的type是不是我想要的那个,该怎么办呢?
用type(obj) is type当然可以
在这里我们还有个办法,用isinstance(obj,type),举个栗子:

import collectionsa=[1,1,2,2,3,3,3]b=collections.Counter(a) #Counter({3: 3, 1: 2, 2: 2})type(b) #<class 'collections.Counter'>isinstance(b,collections.Counter) #True

既然有了type()来判断类型,为什么还有isinstance()呢?
一个明显的区别是在判断子类。
type()不会认为子类是一种父类类型。
isinstance()会认为子类是一种父类类型。
引自:
http://www.pythontab.com/html/2013/pythonjichu_0827/549.html

0 0
原创粉丝点击