isinstance()用来判断一个对象是否是一个已知的类型,isinstance()函数的语法如下:
isinstance(object,classtype)
- object -- 实例对象。
- classtype -- 可以是直接或间接类名、基本类型或者由它们组成的元组。
def isinstance(x, A_tuple): # real signature unknown; restored from __doc__
"""
Return whether an object is an instance of a class or of a subclass thereof.
A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
or ...`` etc.
"""
pass
isinstance()函数的返回值是布尔型,若object的类型是classtype,那么就返回True,否则返回False。
示例代码1:
A = "I love you"
ans = isinstance(A, str)
print("A is str: " + str(ans))
B = ['I love you']
ans = isinstance(B, str)
print("B is str: " + str(ans))
C = ["I love you"]
ans = isinstance(C, list)
print("C is list: " + str(ans))
if not isinstance(C, list):
print("C is not a list")
else:
print("C is a list")
运行效果:
示例代码2:
a = 'str'
b = {"name": "张三"}
# 是元组中的一个返回 True
ret1 = isinstance(a, (str, int, list))
print(ret1)
ret2 = isinstance(b, (str, int, list))
print(ret2)
运行结果:
注意:
isinstance() 与 type() 区别:
- type() 不会认为子类是一种父类类型,不考虑继承关系。
- isinstance() 会认为子类是一种父类类型,考虑继承关系。
如果要判断两个类型是否相同推荐使用 isinstance()。
示例代码3:
class A(object):
pass
class B(A):
pass
print(isinstance(A(), A)) # True
print(type(A()) == A) # True
print(isinstance(B(), A)) # True
print(type(B()) == A) # False
运行结果: