1. 使用`type()`函数:
x = 5
print(type(x)) 输出:
y = "Hello"
print(type(y)) 输出:
z = [1, 2, 3]
print(type(z)) 输出:
2. 使用`isinstance()`函数:
x = 5
print(isinstance(x, int)) 输出:True
y = "Hello"
print(isinstance(y, str)) 输出:True
z = [1, 2, 3]
print(isinstance(z, (list, tuple))) 输出:True
3. 使用`dir()`函数:
x = 5
print(dir(x)) 输出:['__add__', '__and__', '__bool__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__hex__', '__iadd__', '__iand__', '__ifloordiv__', '__ilshift__', '__imatmul__', '__imod__', '__imp__', '__invert__', '__ior__', '__ipow__', '__isub__', '__ixor__', '__iter__', '__itruediv__', '__lshift__', '__lt__', '__matmul__', '__mod__', '__mul__', '__ne__', '__neg__', '__or__', '__pos__', '__pow__', '__rshift__', '__round__', '__seq__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__truediv__', '__xor__']
4. 使用`hasattr()`函数:
class MyClass:
def __init__(self):
self.attribute = "Hello"
obj = MyClass()
print(hasattr(obj, "attribute")) 输出:True
以上方法可以帮助你了解Python中变量的数据类型