在Python中,可以使用type()函数来获取一个对象的类型,然后可以使用if语句来进行类型检查。下面是一个简单的示例:
def check_type(obj):
if type(obj) == int:
print("This is an integer")
elif type(obj) == str:
print("This is a string")
else:
print("Unknown type")
# 测试
check_type(10) # 输出:This is an integer
check_type("hello") # 输出:This is a string
check_type(3.14) # 输出:Unknown type
需要注意的是,在Python中有许多种类型检查的方法,建议根据具体的情况选择最适合的方法。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:Python代码静态类型怎么检查