在很多情况下,需要对类型进程动态判断,因为不同的数据类型不能互相做运算并且各自拥有不同的运算逻辑,所有需要判断对象的类型,常用的是type和isinstance,type更过用于获取对象是什么类型构建的,而isinstance可以判断对象是否继承某个类或对象是否是多个类型中的一个。
变量类型判断
type 只能一次判断一种类型,核心是判断实例对象是由什么类型构建
isinstance 可以判断一种类型也可以判断多种类型,同时还可以判断继承链
__author_ = "北门吹雪"__blog__ = "http://www.cnblogs.com/2bjiujiu/"__email__ = "422083556@qq.com"def check_type(value): """使用isinstance判断变量单个类型""" # 判断变量单个类型,如果是则返回其类型对应的字符 if isinstance(value, int): return "int" elif isinstance(value, float): return "float" elif isinstance(value, bool): return "bool" elif isinstance(value, str): return "str" elif isinstance(value, list): return "list" elif isinstance(value, tuple): return "tuple" elif isinstance(value, set): return "set" elif isinstance(value, dict): return "dict" # 如果都不是则返回不知道 else: return "Unknow Type of {value}".format(value=value)def check_object(value): """使用instance同时判断多个类型""" # 判断变量是否是数字类型 if isinstance(value, (int, float, bool)): return "number" # 判断变量是否有序序列 elif isinstance(value, (str, list, tuple)): return "Ordered sequence" # 判断变量是否是无序序列 elif isinstance(value, (set, dict)): return "Disordered sequence" else: return "Unknow Object of {value}".format(value=value)def use_type(value): """type只能判断变量单个类型,也可以通过 or来进行折中解决""" if type(value) == int: return "int" elif type(value) == float: return "float" else: return "Unknow Type of {value}".format(value=value)if __name__ == '__main__': print(check_type(10)) print(check_type("10")) print(check_object((1, 3, 5))) print(check_object({2, 5, 6})) print(use_type(10)) print(use_type((1, 3)))
判断继承链
class Person(object): def __init__(self, skin, language): self.skin = skin self.language = languageclass Student(Person): def __init__(self,skin, language, name, sex, age, phone_number): # 继承使用父类的析构字段 super(Student, self).__init__(skin=skin, language=language) self.name = name self.sex = sex self.age = age self.phone_number = phone_numberif __name__ == '__main__': beimenchuixue = Student("yellow", "zh-hans", "xiaoMing", "male", 18, "15570911036") # 判断实例xia_ming是否继承于 Persion print(isinstance(beimenchuixue, Person)) print(beimenchuixue.skin)
判断实例对象由什么类型构成
class Class(object): def __init__(self, student_names): self.student_names = student_names def __getitem__(self, item): return self.student_names[item]python_class = Class(["QiNiuYun", "BeiMenChuiXue", "AliYun", "BaiDu"])print(type(python_class))print(type(int))print(type(object))print(type(type))