functionisinstance()You can determine the type of a variable, which can be used in Python built-in data types such asstr、list、dict, can also be used in our custom classes, they are essentially data types.
Assume that there is the followingPerson、ManandWomanThe definition and inheritance relationship are as follows:
class Person(object): def __init__(self, name, gender): = name = gender class Man(Person): def __init__(self, name, gender, score): super(Man, self).__init__(name, gender) = score class Woman(Person): def __init__(self, name, gender, course): super(Woman, self).__init__(name, gender) = course p = Person('Tim', 'Male') m = Man('Bob', 'Male', 88) w = Woman('Alice', 'Female', 'English')
When we get the variablep、m、w When you can useisinstanceJudgement type:
>>> isinstance(p, Person) True # p is Person type>>> isinstance(p, man) False # p is not a Man type>>> isinstance(p, Woman) False # pnoWomantype
This shows that on the inheritance chain, an instance of a parent class cannot be a subclass type, because the sub-analog has more properties and methods than the parent class.
Let's look at m :
>>> isinstance(m, Person) True # m is Person type>>> isinstance(m, Man) True # m is Man type>>> isinstance(m, Woman) False # mnoWomantype
myesManType, notWomanType, this is easy to understand. but,mIt's also a Person type, becauseManInherited from Person, although it has more properties and methods than Person, mIt is also possible to be regarded as a Person example.
This shows that on an inheritance chain, an instance can be regarded as its own type or as its parent class type.
Task
Please think in sequence according to the type conversion of the inheritance chain.wIs it truePerson,Man,Woman,object Type and useisinstance()Judgment to verify your answer.
class Person(object): def __init__(self, name, gender): = name = gender class Man(Person): def __init__(self, name, gender, score): super(Man, self).__init__(name, gender) = score class Woman(Person): def __init__(self, name, gender, course): super(Woman, self).__init__(name, gender) = course w = Woman('Alice', 'Female', 'English') print (isinstance(w,Person)) print (isinstance(w, Man)) print (isinstance(w, Woman)) print (isinstance(w, object )) #Run result#True #False #True #True
This is the article about the detailed explanation of the isinstance() example in Python. For more related contents of python judging type function isinstance(), please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!