如何使用Python中的isinstance()函数检查变量的类型?
发布时间:2023-07-01 23:40:45
在Python中,可以使用isinstance()函数来检查变量的类型。isinstance()函数的语法如下:
isinstance(object, classinfo)
其中,object为需要被检查类型的对象,classinfo为要检查的类型,可以是一个类或者一个由类组成的元组。
下面是使用isinstance()函数检查变量类型的一些示例:
1. 检查整数类型:
num = 10
if isinstance(num, int):
print("num is an integer")
else:
print("num is not an integer")
输出结果为:num is an integer
2. 检查浮点数类型:
num = 10.5
if isinstance(num, float):
print("num is a float")
else:
print("num is not a float")
输出结果为:num is a float
3. 检查字符串类型:
text = "Hello World"
if isinstance(text, str):
print("text is a string")
else:
print("text is not a string")
输出结果为:text is a string
4. 检查列表类型:
lst = [1, 2, 3]
if isinstance(lst, list):
print("lst is a list")
else:
print("lst is not a list")
输出结果为:lst is a list
5. 检查字典类型:
dct = {"name": "John", "age": 30}
if isinstance(dct, dict):
print("dct is a dictionary")
else:
print("dct is not a dictionary")
输出结果为:dct is a dictionary
6. 检查函数类型:
def add(a, b):
return a + b
if isinstance(add, type(lambda: None)):
print("add is a function")
else:
print("add is not a function")
输出结果为:add is a function
7. 检查自定义类的类型:
class Person:
pass
person = Person()
if isinstance(person, Person):
print("person is an instance of Person class")
else:
print("person is not an instance of Person class")
输出结果为:person is an instance of Person class
除了单个类型检查外,isinstance()函数还可以检查对象是否属于一个类型元组中的任意一个类型。例如:
value = 10
if isinstance(value, (int, float, str)):
print("value is an integer, float or string")
else:
print("value is not an integer, float or string")
输出结果为:value is an integer, float or string
总结起来,使用isinstance()函数可以方便地进行类型判断,帮助我们在编写代码时处理不同类型的对象。
