In Python, use isinstance () to determine the variable type, pythonisinstance
I. isinstance ()
In Python, you can use the type () and isinstance () functions to determine the object type. The isinstance () function is more convenient to use than the type function.
Copy codeThe Code is as follows:
# Coding = UTF-8
A = 10
Def B ():
Pass
Print isinstance (a, (int, str ))
Print isinstance (a, (float, str ))
Print isinstance (B, (str, int ))
Class c:
Pass
Obj = c ()
Print isinstance (obj, (c, int ))
Execution result:
Copy codeThe Code is as follows:
True
False
False
True
Ii. Differences between isinstance and type
The difference between isinstance and type is:
Copy codeThe Code is as follows:
Class:
Pass
Class B ():
Pass
Isinstance (A (), A) # returns True
Type (A () = A # returns True
Isinstance (B (), A) # returns True
Type (B () = A # returns False
The difference is that subclass and other types will not work. Therefore, we strongly recommend that you do not use type to determine the object type.
How does python determine that a variable is a list?
This does not seem to be the case with isinstance. I usually use type
X = int (5)
If type (x) = int: print "x is interger ."
Else: print "false ."
Isinstance can be used to determine whether a variable belongs to a class. It should be correct in python.
If type (x) = list: pass
If type (x) = dict: pass
What are the functions and usage of isinstance () in python?
Isinstance is rarely used. It is used only when some object-oriented production models are used. It is usually used to determine the inheritance relationship of a class.
>>> Class:
... V1 = 1
...
>>> Class B:
... V2 = 2
...
>>> Class c ():
... V1 = 3
...
>>> X = c ()
>>> Isinstance (x,)
True
>>> Isinstance (x, c)
True
>>> Isinstance (x, B)
False
>>>