如何在Python中检查变量(对象)的类型
Python不是一种类型化的语言。这意味着对象是通过它们可以做什么而不是它们是什么来标识的。在本教程中,我们将学习如何在Python中检查和打印变量类型
Python数据是对象
遵循Python,我们称之为对象模型,这是什么意思?
每个数字,字符串,数据结构,函数,类,模块等都存在于Python解释器中自己的"框"中,该框称为" Python对象"。
每个对象都有一个标识,一个类型和一个值。
例如,当我们编写" a = 42"时,将创建一个值为42的整数对象。
在Python中,对象是至少包含以下内容的数据块:
定义其功能的"类型"
唯一的
id
可以将其与其他对象区分开与其类型一致的"值"
跟踪该对象使用频率的"引用计数"
python中的不同内置对象类型
下表显示了Python内置的受支持对象类型。
第二列(
Type
)包含该类型的Python名称。第三列(
Mutable?
)表示创建后是否可以更改该值"示例"显示了该类型的一个或者多个文字示例。
名称 | 类型 | 可变? | 示例 |
---|---|---|---|
布尔值 | bool | no | 真,假 |
整数 | int | no | 53,5000,5|400 |
浮点 | 浮点 | 否 | 2.56,3.1e5 |
复合 | 复合 | 否 | 3j,5+9j |
文本字符串 | str | no | 'abcd','def','ghi' |
列表 | 列表 | 是 | ['abc','def','ghi'] |
Tuple | Tuple | no | ('abc','def',1997,2000) (1,2,3,4,5) |
字节 | 字节 | 否 | b'ab\xff' |
ByteArray | ByteArray | 否 | ByteArray(…) |
Set | Set | yes | 设置([3,5,7]) |
FrozenSet | FrozenSet | 否 | FrozenSet(['Elsa','Otto') |
字典 | dict | yes | {game':'bingo','dog':'dingo','drummer':'Ringo'} |
检查Python中的变量类型
在Python中,我们可以使用type()
和isinstance()
来检查和打印变量的类型。我们将通过示例详细介绍这两个功能:
type()函数
内置函数
type()
可访问对象的类型。类型上没有特殊的操作。标准模块类型定义了所有标准内置类型的名称。
类型是这样写的:
<class'int'>
类类型(对象)
返回对象的"类型"。
该类型作为定义为内置对象或者在types模块中的类型对象返回。
对象的类型本身就是对象。
此类型对象是唯一定义的,并且对于给定类型的所有实例始终是相同的。
因此,可以使用is运算符比较类型。
为所有类型对象分配了可用于执行类型检查的名称。
在这个python脚本中," type(var)"正在检查" var"的值是否为" integer"类型。
#!/usr/bin/env python3 var = 10 # Check if 10 (which is the value of var) is integer if type(var) is int: print('Is an integer')
输出:
Is an integer
类似于检查变量是否为"列表"类型
#!/usr/bin/env python3 # Assigned a list to var object var = ['10','abcd','1234'] # Check if the value of var contains list type if type(var) is list: print('Is a list')
输出:
Is a list
或者使用type()
检查变量类型的另一种方法
#!/usr/bin/env python3 # Assigned a list to var object var = ['10','abcd','1234'] # Check if the value of var contains list type if type(var) == list: print('Is a list')
输出:
Is a list
要打印变量类型,我们可以使用type()函数调用print。
#!/usr/bin/env python3 # Assigned a list to var object var = ['10','abcd','1234'] # Print the type of variable print(type(var))
输出:
<class 'list'>
类类型(名称,基数,字典)
创建一个新的类型对象(与定义新类相同)。
"名称"是类型的名称,并成为" name"属性
bases是基类的元组,并成为__bases__属性
dict是包含对应于类主体的定义的字典,并成为__dict__属性。
type(name,bases,dict)的用例是当我们想在运行时动态生成类时。
在这个例子中,我们创建一个类,并打印各个属性:
#!/usr/bin/env python3 class NewClass: """NewClass Documentation""" var = 'string' print (NewClass.__class__) print(NewClass.__bases__) print(NewClass.__dict__) print(NewClass.__doc__)
输出:
<class 'type'> (<class 'object'>,) {'__module__': '__main__', '__doc__': 'NewClass Documentation', 'var': 'string', '__dict__': <attribute '__dict__' of 'NewClass' objects>, '__weakref__': <attribute '__weakref__' of 'NewClass' objects>} NewClass Documentation
现在我们可以使用type(name,bases,dict)
函数实现相同的功能并定义一个类。
#!/usr/bin/env python3 NewClass1 = type('NewClass1', (object,), {'__doc__': 'NewClass1 Documentation', 'var': 'string'}) print (NewClass1.__class__) print(NewClass1.__bases__) print(NewClass1.__dict__)
输出:
<class 'type'> (<class 'object'>,) {'__doc__': 'NewClass1 Documentation', 'var': 'string', '__module__': '__main__', '__dict__': <attribute '__dict__' of 'NewClass1' objects>, '__weakref__': <attribute '__weakref__' of 'NewClass1' objects>} NewClass1 Documentation
isinstance()函数
isinstance()函数用于验证输入参数类型。
如果object参数是classinfo参数或者其(直接,间接或者虚拟)子类的实例,则返回True。
如果object不是给定类型的对象,则该函数始终返回False。
语法:
isinstance(object, classinfo)
其中
必须检查的"对象"
classinfo可以是一个类,类型,也可以是一个类和/或者类型的元组。
提示:
在Python 3.0中,类型是类,因此类型没有特殊情况
#!/usr/bin/env python3 # Define var object var = 'some value' # Check variable type and return boolean value print(isinstance(var, str))
Output
返回布尔值:
True
同样在" if"条件下
#!/usr/bin/env python3 # Define var object var = 'some value' # Check variable type and return boolean value if isinstance(var, str): print("Is a string")
输出:
Is a string
如果要检查对象的类型是否在该元组中,则isinstance()可以接受一个元组类型:
#!/usr/bin/env python3 # Define var object var = 4.5 # Check variable type using tuple class and return boolean value if isinstance(var, (int, float)): print("Is either an integer or float type")
请注意第二个括号,围绕着我们传入的两个值类型。这个括号表示一个元组,数据结构之一。 输出
:
Is either an integer or float type
type()vs isinstance()
type()和isinstance()函数都可以用来检查和打印变量的类型,但是建议使用内置函数isinstance()来测试对象的类型,因为它也需要子类。
此外,通过isinstance()
,我们还可以将布尔值返回为True或者False,这些值可以用作决策制定
我们可以在" type()"和" isinstance()"之间有何区别?