# 示例代码:使用 type() 函数
# 定义一个整数变量
x = 5
print(f"变量 x 的类型是: {type(x)}") # 输出: <class 'int'>
# 定义一个字符串变量
y = "Hello, World!"
print(f"变量 y 的类型是: {type(y)}") # 输出: <class 'str'>
# 定义一个列表变量
z = [1, 2, 3, 4, 5]
print(f"变量 z 的类型是: {type(z)}") # 输出: <class 'list'>
# 使用 type() 创建类
MyClass = type('MyClass', (object,), {'attribute': 'value'})
print(f"MyClass 是一个类,其类型是: {type(MyClass)}") # 输出: <class 'type'>
print(f"MyClass 的属性值是: {MyClass.attribute}") # 输出: value
# 创建 MyClass 的实例
my_instance = MyClass()
print(f"my_instance 是 MyClass 的实例,其类型是: {type(my_instance)}") # 输出: <class '__main__.MyClass'>
type() 函数可以用于获取变量的类型。type(x) 返回 <class 'int'>,表示 x 是一个整数类型的变量。type(y) 返回 <class 'str'>,表示 y 是一个字符串类型的变量。type(z) 返回 <class 'list'>,表示 z 是一个列表类型的变量。type() 还可以用来动态创建类。在最后一个例子中,我们使用 type() 创建了一个名为 MyClass 的类,并给它添加了一个属性 attribute。然后我们创建了该类的一个实例 my_instance,并检查其类型。上一篇:python pynput
下一篇:python矩阵运算
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站