注:使用函数显示地检查类型会毁掉多态,尽量避免使用。
判断基本类型:
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
判断基本类型:
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
判断继承关系,一个类是否另一个类的子类:
1 class Animal(object): 2 pass 3 class Dog(Animal): 4 pass 5 6 >>>issubclass(Dog,Animal) 7 True如果想知道类的基类,用特殊属性__bases__:
Dog.__bases__
转载于:https://www.cnblogs.com/utopia8/p/5131745.html