判断对象类型

python/check_datatypes2026-08-24 19:46:25

在Python中,可以使用内置的 type() 函数和 isinstance() 函数来判断对象的类型。

type() 函数

type() 函数返回变量的类型。可以将返回的类型与特定类型进行比较。

x = 10
y = 3.14
z = "Hello"

print(type(x))  # 输出: <class 'int'>
print(type(y))  # 输出: <class 'float'>
print(type(z))  # 输出: <class 'str'>

# 比较类型
if type(x) == int:
    print("x is an integer")
if type(y) == float:
    print("y is a float")
if type(z) == str:
    print("z is a string")

isinstance() 函数

isinstance() 函数用于检查一个对象是否是特定类或类型的实例。

语法:isinstance(object, classinfo),其中 object 是要检查的对象,classinfo 是类型或类型的元组。

x = 10
y = 3.14
z = "Hello"
a = [1, 2, 3]

print(isinstance(x, int))    # 输出: True
print(isinstance(y, float))  # 输出: True
print(isinstance(z, str))    # 输出: True
print(isinstance(a, list))   # 输出: True

# 检查多个类型
if isinstance(x, (int, float)):
    print("x is either an integer or a float")

本页目录