所谓内置函数,就是无需import,就可以直接使用的函数
1. python2 & python3 内置函数统计
python2: 76 个
python3: 69 个
2. Python2与Python3公有的内置函数
2.1 数学计算(7个)
| 序号 | 函数 | 作用 | 示例 |
|---|---|---|---|
| 1 | abs() | 求绝对值 | >>> abs(-1)1 |
| 2 | round() | 将小数四舍五入,默认保留0位小数 | >>> round(1.4)1 >>> round(1.55, 1)1.6 |
| 3 | pow() | 指数求幂, 等价于幂运算符: x**y | >>> pow(2, 3)8 |
| 4 | min() | 求可迭代对象的最小值, 传入字典,需要提供key参数,返回最小值对应键 | >>> min([2, 1, 3])1 >>> d={'a': 2, 'b':1}; min(d, key=d.get)b |
| 5 | max() | 求可迭代对象的最大值, 传入字典,需要提供key参数,返回最大值对应键 | >>> max([2, 1, 3])3 >>> d={'a': 2, 'b':1}; max(d, key=d.get)a |
| 6 | sum() | 求可迭代对象的和, 可提供初始累加值,默认为0 | >>> sum([1, 2, 3])6 >>> sum([1, 2, 3], 1)7 |
| 7 | divmod() | 返回一对商和余数 | >>> divmod(5, 2)(2, 1) |
2.2 数据操作(9个)
| 序号 | 函数 | 作用 | 示例 |
|---|---|---|---|
| 1 | len() | 返回元素个数 | >>> len([1, 2])2 |
| 2 | sorted() | 排序 | >>> sorted([2, 1])[1, 2] >>> sorted([{'a': 2, 'b': '1'}, {'a': 1, 'b': 2}], key=lambda x: x['a'])[{'a': 1, 'b': 2}, {'a': 2, 'b': '1'}] >>> d = {'a':2, 'b':1}; sorted(d, key=d.get, reverse=True)['a', 'b'] |
| 3 | reversed() | 反向, 返回iterator对象 | >>> list(reversed([2, 1]))[1, 2] |
| 4 | slice() | 返回slice(切片)对象, 等价于[start:stop:step] | >>> [1, 2, 3][slice(1, 2)][2] |
| 5 | next() | 调用__next__() 方法获取下一个元素 | >>> next(iter([1,2,3]))1 |
| 6 | all() | 所有元素为真,返回真 | >>> all([True, True])True |
| 7 | any() | 任一元素为真,返回真 | >>> any([True, False])True |
| 8 | filter() | 返回为真的元素 | >>> [i for i in filter(None, [True, False])][True] >>> list(filter(lambda x: x['s'], [{'s': False}, {'s': None}, {'s': True}]))[{'s': True}] |
| 9 | map() | 对元素进行处理,返回新的迭代器 | >>> list(map(lambda x: round(x), [1.4, 1.5]))[1, 2] |
2.3 文件&系统(6个)
| 序号 | 函数 | 作用 | 示例 |
|---|---|---|---|
| 1 | open() | 打开文件 | >>> with open('1.txt', 'w') as f:... f.write('hello world!')12 >>> with open('1.txt', 'r') as f:... f.read()'hello world!' |
| 2 | input() | 等待获取用户输入 | >>> input('are you ok?\n')are you ok? fuck 'fuck' |
| 3 | print() | 打印到标准输出 | >>> print('hello world!')hello world! |
| 4 | locals() | 更新并返回表示当前本地符号表的字典 | >>> locals() |
| 5 | globals() | 返回表示当前全局符号表的字典 | >>> globals() |
| 6 | vars() | 返回对象的__dict__属性;不带参数, 等价locals |
>>> class Klass:... __dict__ = ['a', 'b']>>> vars(Klass())['a', 'b'] |
2.4 类(12个)
| 序号 | 函数 | 作用 | 示例 |
|---|---|---|---|
| 1 | type() | 返回对象类型, 等效于object.__class__ | >>> type({'a': 1})<class 'dict'> |
| 2 | isinstance() | 对象是否是类的实例 | >>> k = Klass(); isinstance(k, Klass)True |
| 3 | issubclass() | 类是否是父类的子类 | >>> class SubKlass(Klass):... pass>>> issubclass(SubKlass, Klass)True |
| 4 | classmethod() | decorator把方法封装成类方法 | >>> class C:... @classmethod... def f(cls):... pass |
| 5 | staticmethod() | decorator将方法转换为静态方法 | >>> class C:... @staticmethod... def f(cls):... pass |
| 6 | super() | 返回一个代理对象,将方法调用 委托给父类或兄弟类。了解super设计协作类 |
>>> class Animal:... def eat(self): print('wa wa ...')>>> class Dog(Animal):... def eat(self):... super().eat()... print('give me meat.')>>> Dog().eat()wa wa ... give me meat. |
| 7 | hasattr() | 对象是否具有属性 | >>> dog = Dog(); hasattr(dog, 'name')False |
| 8 | setattr() | 给对象添加新属性 | >>> setattr(dog, 'name', "旺财") |
| 9 | getattr() | 获取对象属性值 | >>> getattr(dog, 'name')'旺财' |
| 10 | dir() | 返回模块或对象的有效属性列表 | >>> dir(dog)[..., 'eat', 'name'] |
| 11 | delattr() | 删除对象属性 | >>> delattr(dog, 'name') |
| 12 | property() | 返回property属性 | >>> class Klass:... def __init__(self):self._x = 0... @property... def x(self):return self._x>>> Klass().x0 |
2.5 数据类型创建&转换(23个)
| 序号 | 函数 | 作用 | 示例 |
|---|---|---|---|
| 1 | int() | 返回十进制整数, 默认传入为十进制 |
>>> int()0 >>> int('f', 16)15 >>> int('g', 17)16 |
| 2 | float() | 返回小数 | >>> float()0.0 >>> float('1e-2')0.01 >>> float('-Infinity')-inf |
| 3 | str() | 将数字或对象转换成字符串 了解更多 | >>> str(1.5)'1.5' >>> str([1, 2, 3])'[1, 2, 3]' |
| 4 | bool() | 返回一个布尔值 | >>> bool(0)False >>> bool(None)False >>> bool([])False >>> bool({})False >>> bool(1)True |
| 5 | tuple() | 返回一个元组,了解更多 | >>> tuple([1, 2, 3])(1, 2, 3) >>> tuple({1, 2, 3})(1, 2, 3) >>> tuple(range(1, 3))(1, 2) |
| 6 | set() | 返回一个集合 | >>> set([1, 2, 3]){1, 2, 3} >>> set((1, 2, 3)){1, 2, 3} >>> set(range(1, 3)){1, 2} |
| 7 | list() | 返回一个列表 | >>> list((1, 2, 3))[1, 2, 3] >>> list({1, 2, 3})[1, 2, 3] >>> list(range(1, 3))[1, 2] |
| 8 | dict() | 返回一个字典 | >>> dict(one=1, two=2, three=3){'one': 1, 'two': 2, 'three': 3} >>> dict([('two', 2), ('one', 1), ('three', 3)]){'two': 2, 'one': 1, 'three': 3} >>> dict(zip(['one', 'two', 'three'], [1, 2, 3])){'one': 1, 'two': 2, 'three': 3} |
| 9 | complex() | 返回一个复数 | >>> complex(1, 2)(1+2j) |
| 10 | bin() | 返回一个二进制字符串 | >>> bin(10)'0b1010' |
| 11 | oct() | 返回一个八进制字符串 | >>> oct(10)'0o12' |
| 12 | hex() | 返回一个十六进制字符串 | >>> hex(10)'0xa' |
| 13 | range() | 返回一个range对象 | >>> list(range(1, 9, 2))[1, 3, 5, 7] |
| 14 | zip() | 创建一个聚合了来自每个可迭代对象中的元素的迭代器 | >>> list(zip((1, 4, 7), [2, 5, 8], range(3, 10, 3)))[(1, 2, 3), (4, 5, 6), (7, 8, 9)] |
| 15 | enumerate() | 返回一个枚举对象 | >>> list(enumerate(['a', 'b', 'c']))[(0, 'a'), (1, 'b'), (2, 'c')] >>> list(enumerate(['a', 'b', 'c'], 1))[(1, 'a'), (2, 'b'), (3, 'c')] |
| 16 | iter() | 返回一个迭代器对象 | >>> next(iter([1, 2, 3]))1 |
| 17 | object() | 返回一个没有特征的新对象 | >>> dir(object())['__class__', ...] |
| 18 | bytearray() | 返回一个新的 bytes 数组 | >>> [i for i in bytearray('hello world!', encoding='utf8')][104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33] |
| 19 | hash() | 返回对象的哈希值 | >>> hash('hello')116457751260220756 |
| 20 | id() | 返回对象的“标识值” | >>> id('hello')2590383091640 |
| 21 | chr() | 返回整数Unicode的字符串格式 | >>> chr(8364)'€' |
| 22 | ord() | Unicode字符转整数 | >>> ord('€')8364 |
| 23 | frozenset() | 返回一个新的frozenset对象 | >>> frozenset([1, 2, 3])frozenset({1, 2, 3}) |
2.6 其他(8个)
| 序号 | 函数 | 作用 | 示例 |
|---|---|---|---|
| 1 | callable() | 是否可调用 | >>> callable(abs)True |
| 2 | compile() | 将source编译成代码或AST对象 | >>> compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1) |
| 3 | eval() | 对表达式字符串解析求值 | >>> x = 1; eval('x+1')2 |
| 4 | help() | 启动内置的帮助系统(此函数主要在交互式中使用) | >>> help() |
| 5 | repr() | 返回对象的可打印表示形式的字符串 | >>> repr(Klass())'<main.Klass object at 0x000001CF7A8D2CC0>' |
| 6 | memoryview() | 返回由给定实参创建的“内存视图”对象 | >>> memoryview(bytearray([1, 2]))<memory at 0x000001CF7AA357C8> |
| 7 | format() | 返回格式化字符串 | >>> format(value[, format_spec]) |
| 8 | __import__() | 此函数会由import语句发起调用,日常 Python 编程中不需要用到的高级函数 | - |
3. Python2与Python3私有的内置函数
3.1 python3新增函数(4个):
- ascii()
- breakpoint()
- bytes()
- exec()
3.1 python2有python3移除函数(11个):
- basestring()
- cmp()
- execfile()
- file()
- long()
- raw_input()
- reduce()
- reload()
- unichr()
- unicode()
- xrange()
4 python2.7.16 与 python3.7.4 对照表(共80个)
| 序号 | 函数 | python2.7.16 | python3.7.4 |
|---|---|---|---|
| 1 | abs() | yes | yes |
| 2 | all() | yes | yes |
| 3 | any() | yes | yes |
| 4 | ascii() | no | yes |
| 5 | basestring() | yes | no |
| 6 | bin() | yes | yes |
| 7 | bool() | yes | yes |
| 8 | breakpoint() | no | yes |
| 9 | bytearray() | yes | yes |
| 10 | bytes() | no | yes |
| 11 | callable() | yes | yes |
| 12 | chr() | yes | yes |
| 13 | classmethod() | yes | yes |
| 14 | cmp() | yes | no |
| 15 | compile() | yes | yes |
| 16 | complex() | yes | yes |
| 17 | delattr() | yes | yes |
| 18 | dict() | yes | yes |
| 19 | dir() | yes | yes |
| 20 | divmod() | yes | yes |
| 21 | enumerate() | yes | yes |
| 22 | eval() | yes | yes |
| 23 | exec() | no | yes |
| 24 | execfile() | yes | no |
| 25 | file() | yes | no |
| 26 | filter() | yes | yes |
| 27 | float() | yes | yes |
| 28 | format() | yes | yes |
| 29 | frozenset() | yes | yes |
| 30 | getattr() | yes | yes |
| 31 | globals() | yes | yes |
| 32 | hasattr() | yes | yes |
| 33 | hash() | yes | yes |
| 34 | help() | yes | yes |
| 35 | hex() | yes | yes |
| 36 | id() | yes | yes |
| 37 | input() | yes | yes |
| 38 | int() | yes | yes |
| 39 | isinstance() | yes | yes |
| 40 | issubclass() | yes | yes |
| 41 | iter() | yes | yes |
| 42 | len() | yes | yes |
| 43 | list() | yes | yes |
| 44 | locals() | yes | yes |
| 45 | long() | yes | no |
| 46 | map() | yes | yes |
| 47 | max() | yes | yes |
| 48 | memoryview() | yes | yes |
| 49 | min() | yes | yes |
| 50 | next() | yes | yes |
| 51 | object() | yes | yes |
| 52 | oct() | yes | yes |
| 53 | open() | yes | yes |
| 54 | ord() | yes | yes |
| 55 | pow() | yes | yes |
| 56 | print() | yes | yes |
| 57 | property() | yes | yes |
| 58 | range() | yes | yes |
| 59 | raw_input() | yes | no |
| 60 | reduce() | yes | no |
| 61 | reload() | yes | no |
| 62 | repr() | yes | yes |
| 63 | reversed() | yes | yes |
| 64 | round() | yes | yes |
| 65 | set() | yes | yes |
| 66 | setattr() | yes | yes |
| 67 | slice() | yes | yes |
| 68 | sorted() | yes | yes |
| 69 | staticmethod() | yes | yes |
| 70 | str() | yes | yes |
| 71 | sum() | yes | yes |
| 72 | super() | yes | yes |
| 73 | tuple() | yes | yes |
| 74 | type() | yes | yes |
| 75 | unichr() | yes | no |
| 76 | unicode() | yes | no |
| 77 | vars() | yes | yes |
| 78 | xrange() | yes | no |
| 79 | zip() | yes | yes |
| 80 | __import__() | yes | yes |
参考
- [1] docs.python.org/zh-cn/3/lib…
- [2] docs.python.org/zh-cn/2/lib…
- [3] 菜鸟教程 Python3 内置函数
- [4] 菜鸟教程 Python 内置函数
- [5] Python3 术语对照表
坚持写专栏不易,如果觉得本文对你有帮助,记得点个赞。感谢支持!
- 个人网站: kenblog.top
- github 站点: kenblikylee.github.io

微信扫描二维码 获取最新技术原创