python的type()函数功能和实例,返回值类型

python的type()函数

type()是python的另一个用于查询的内置函数,type()函数的功能主要用于查询python对象的数据类型。如果type()函数的参数个数为1的话,返回值类型是str字符串类型的值,如果是三个的话,返回一个新的类型的类型值(具体可以看下方的实例)。鄙人的python开发经验中,用type()比较多的地方是在调试、处理python程序中的bug。


python中type()函数的返回值类型

<class 'type'>

type()函数的实例代码

>>> type(1)
<class 'int'>
>>> type([])
<class 'list'>
>>> type(())
<class 'tuple'>
>>> type({})
<class 'dict'>
>>> type('')
<class 'str'>
>>> type(type(1))
<class 'type'>

代码解析

如上代码,type(type(1))中,将type(1)的返回值作为对象传递给type(),查询的结果得到的是<class 'type'>类型。


type()三个参数的情况

ptyhon的type()函数中,存在三个参数的情况,这个时候,type()将返回一个新的类型,类似于用class创建一个新的类。三个参数如下:

  • 第一个参数是一个str字符串类型的值,用于表示新创建的类的名称;
  • 第二个参数是个元组,是新的类所继承的父类,类似于class中类的继承用法;
  • 第三个参数是一个dict字典,用来设置类的属性、类方式、静态方法,其中key为属性名,value为属性值;
>>> newclass = type("newclass",(object,),{"a":1})
>>> newclass

>>> n = newclass() #实例化
>>> n.a
1

全栈后端 / python教程 :


























Copyright © 2022-2024 笨鸟工具 x1y1z1.com All Rights Reserved.