类型检查

注:使用函数显示地检查类型会毁掉多态,尽量避免使用。

 

  • type()

判断基本类型:

1 >>> type(123)
2 <type 'int'>
3 >>> type('str')
4 <type 'str'>
5 >>> type(None)
6 <type 'NoneType'>

 函数或者类:

1 >>> type(abs)
2 <type 'builtin_function_or_method'>
3 >>> type(a)
4 <class '__main__.Animal'>

 types模块:

1 >>> import types
2 >>> type('abc')==types.StringType
3 True
4 >>> type(u'abc')==types.UnicodeType
5 True
6 >>> type([])==types.ListType
7 True
8 >>> type(str)==types.TypeType
9 True

 

 

  • isinstance()

判断基本类型:

1 >>> isinstance('a', str)
2 True
3 >>> isinstance('a', (str, unicode))
4 True
5 >>> isinstance(u'a', (str, unicode))
6 True

 判断对象是否一个类的实例:

1 >>> a = Animal()
2 >>> d = Dog()
3 >>> h = Husky()
4 
5 >>> isinstance(h, Husky)
6 True
7 >>> isinstance(h, Dog)
8 True

 

  •  issubclass()

 判断继承关系,一个类是否另一个类的子类:

1 class Animal(object):
2     pass
3 class Dog(Animal):
4     pass
5 
6 >>>issubclass(Dog,Animal)
7 True

 如果想知道类的基类,用特殊属性__bases__: 

Dog.__bases__

 

posted @ 2016-01-14 21:52  utopia_8  阅读(168)  评论(0)    收藏  举报