The judgment type function isinstance () can determine the type of a variable that can be used in Python's built-in data types such as STR, list, dict, or in our custom classes, which are essentially data types. Assume that the definition and inheritance of the following person, Student, and Teacher are as follows:classPerson (Object): Def __init__ (self, Name, gender): Self.name=name Self.gender=GenderclassStudent: def __init__ (self, name, gender, score): Super (Student, self). __INIT__ (name, gender) Self.score=scoreclassTeacher: def __init__ (self, name, gender, course): Super (Teacher, self). __INIT__ (name, gender) Self.course=Coursep= Person ('Tim','Male') s= Student ('Bob','Male', the) T= Teacher ('Alice','Female','中文版'when we get the variable p, s, T, we can use isinstance to determine the type:>>>isinstance (p, person) True # p is the person type>>>isinstance (P, Student) False # p is not a Student type>>>isinstance (P, Teacher) False # p is not a Teacher type This indicates that an instance of a parent class cannot be a subclass type on an inheritance chain because the child analogy parent has more properties and methods. We re-examine s:>>>Isinstance (S, person) True # s is the person type>>>Isinstance (S, Student) True # s is the Student type>>>Isinstance (S, Teacher) False # s is not Teacher type S is a student type, not a Teacher type, which is easy to understand. However, S is also the person type because student inherits from person, although it has more properties and methods than person, but it is also possible to consider S as an instance of person. This means that on an inheritance chain, an instance can be regarded as its own type, or as the type of its parent class. Tasks, depending on the type of inheritance chain, consider whether T is Person,student,teacher,ObjectType, and use Isinstance () judgment to verify your answer.
class Person (object): def __init__ (self, Name, gender): self.name = name Self.gender = Genderclass Student ( Person): def __init__ (self, name, gender, score): super (Student, self). __INIT__ (name, gender) Self.score = Scoreclass Teacher: def __init__ (self, name, gender, course): super (Teacher, self). __INIT__ (Name, gender) Self.course = Courset = Teacher (' Alice ', ' Female ', ' 中文版 ') print isinstance (t, person) print isinstance (t, Student) print isinstance (t, Teacher) print isinstance (t, object)
Python type judgment--isinstance function