Python type() 函数是一个内置函数,它返回指定对象的类型,通常用于调试目的。type() 函数的两个主要用例如下 -
当我们向此函数传递单个参数时,它会返回给定对象的类型。
当传递三个参数时,它允许动态创建新类型对象。
语法
以下是 Python type() 函数的语法 -
type(object, bases, dict) # or type(object)
参数
Python type() 函数接受两个参数 -
返回值
Python type() 函数返回给定对象的类型。如果我们传递三个参数,它将返回一个新的类型对象。
type() 函数示例
练习以下示例来理解 Python 中 type() 函数的使用:
示例:使用 type() 函数
以下示例显示了 Python type() 函数的基本用法。在下面的代码中,我们显示了最常用数据类型的类。
var1 = 5
var2 = 5.2
var3 = 'hello'
var4 = [1,4,7]
var5 = {'Day1':'Sun','Day2':"Mon",'Day3':'Tue'}
var6 = ('Sky','Blue','Vast')
print(type(var1))
print(type(var2))
print(type(var3))
print(type(var4))
print(type(var5))
print(type(var6))
以下是上述代码的输出 -
<class 'int'>
<class 'float'>
<class 'str'>
<class 'list'>
<class 'dict'>
<class 'tuple'>
<class 'float'>
<class 'str'>
<class 'list'>
<class 'dict'>
<class 'tuple'>
示例:使用 type() 函数获取类的类型
名为 “type” 的类是一个超类,所有其他类都是从该超类派生的。type object 也是此类的一个实例。因此,将 type() 函数应用于 Python 类将返回 “class type” 作为结果。
print("Displaying the type of Python classes:")
print("Type of int class is", type(int))
print("Type of dict class is", type(dict))
print("Type of list class is", type(list))
print("Type of type class is", type(type))
上述代码的输出如下 -
Displaying the type of Python classes:
Type of int class is <class 'type'>
Type of dict class is <class 'type'>
Type of list class is <class 'type'>
Type of type class is <class 'type'>
Type of int class is <class 'type'>
Type of dict class is <class 'type'>
Type of list class is <class 'type'>
Type of type class is <class 'type'>
示例:使用 type() 函数创建新的类型对象
如果我们向 type() 函数传递三个参数,它将创建一个新的类型对象。在下面的代码中,我们创建了 “qikepu” 作为主类,一个对象作为基类,以及一个具有两个键和值的字典。
Object = type("qikepu", (object, ), dict(loc="Hyderabad", rank=1))
print(type(Object))
print(Object)
以下是上述 Python 代码的输出 -
<class 'type'>
<class '__main__.qikepu'>
<class '__main__.qikepu'>