欢迎各位兄弟 发布技术文章
这里的技术是共享的
在 Python 中,你可以使用内置函数 type()
或 isinstance()
来判断变量的类型。下面是这两种方法的详细说明和示例:
type()
函数type()
函数返回变量的具体类型。
python深色版本x = 10 print(type(x)) # <class 'int'> y = "Hello, World!" print(type(y)) # <class 'str'> z = [1, 2, 3] print(type(z)) # <class 'list'> a = {"name": "Alice", "age": 30} print(type(a)) # <class 'dict'>
isinstance()
函数isinstance()
函数用于检查变量是否属于某个特定类型或某些类型之一。它返回一个布尔值。
python深色版本x = 10 print(isinstance(x, int)) # True y = "Hello, World!" print(isinstance(y, str)) # True z = [1, 2, 3] print(isinstance(z, list)) # True a = {"name": "Alice", "age": 30} print(isinstance(a, dict)) # True # 检查多个类型 b = 3.14 print(isinstance(b, (int, float))) # True c = 100 print(isinstance(c, (int, float, str))) # True d = [1, 2, 3] print(isinstance(d, (list, tuple))) # True
isinstance()
还可以用于检查对象是否是某个类的实例或其子类的实例。
python深色版本class Animal:
pass
class Dog(Animal):
pass
dog = Dog()
print(isinstance(dog, Animal)) # True
print(isinstance(dog, Dog)) # True
print(isinstance(dog, object)) # True
你也可以使用 type()
和 isinstance()
来判断基本类型。
python深色版本x = 10 print(type(x) == int) # True y = "Hello, World!" print(type(y) == str) # True z = [1, 2, 3] print(type(z) == list) # True a = {"name": "Alice", "age": 30} print(type(a) == dict) # True
使用 type()
函数可以获取变量的具体类型。
使用 isinstance()
函数可以检查变量是否属于某个特定类型或某些类型之一,还可以用于检查子类关系。
isinstance()
更灵活,推荐在需要检查多个类型或子类关系时使用。
希望这些方法能帮助你判断变量的类型。如果有更多具体的需求或问题,请告诉我!