isinstance()用来判断一个对象是否是一个已知的类型,isinstance()函数的语法如下:
isinstance(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。
示例代码:
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")
运行效果:
|