In Python use the isinstance of to determine the variable type
- 2020-04-02 14:00:57
- OfStack
One, the isinstance ()
In Python, you can use two functions, type() and isinstance(), to determine the type of an object, and the isinstance() function is more convenient than type.
# 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 results:
True
False
False
True
Ii. Difference between isinstance and type
The difference between isinstance and type is:
class A:
pass
class B(A):
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 it doesn't work for types like subclass, so it's highly recommended that you don't use type to determine the type of an object.