Python 基础教程

Python 高级教程

Python 相关应用

Python 笔记

Python FAQ

original icon
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.knowledgedict.com/tutorial/python-builtin-class_type.html

Python type 内置类

Python 内置类 Python 内置类


type属于内置类,存在于builtins模块中。

type内置类有两种使用方式:

  1. 构造方法传一个参数时,type(x)等价于x.__class__,即x所属的类型对象;
  2. 构造方法传三个参数时,创建一个新的类型;

语法

def __init__(cls, what, bases=None, dict=None)

参数

  • what:当只传一个参数时表示对象,当传三个参数时表示类的名称,字符串形式;
  • bases:继承的父类集合,注意Python支持多重继承,如果只有一个父类,注意tuple的单元素写法;
  • dict:class的方法名称与函数绑定;

示例:

print(type(188))
print(type(1.88))
print(type(1 + 88j))
print(type('tool188'))
print(type((188, '188')))
print(type(True))
print(type([1, 2]))
print(type({'tool': 188}))


def fn(self):
    print('fn')


Test = type('Test', (object,), dict(tt=fn))
a = Test()
a.tt()

输出结果为:

<class 'int'>
<class 'float'>
<class 'complex'>
<class 'str'>
<class 'tuple'>
<class 'bool'>
<class 'list'>
<class 'dict'>
fn