Python 内置函数

Python 解释器内置了很多函数,不用 import 即可使用这些内置函数。本小节讲解了 Python 中常见的内置函数,我们将这些函数分为 7 大类:

类别 功能
系统帮助 获取函数的使用帮助
文件 IO 读取标准输入、写标准输出、打开文件
类型转换 将整数转换为字符串、将字符串转换为整数
数学运算 常见的数学运算函数,例如:max 和 min
复合数据类型 列表、元组、字典等数据类型的构造
对序列的操作 对序列进行排序、筛选、映射
面向对象相关 判断类型之间的归属关系

1. 系统帮助

1.1 列出对象的属性

>>> import sys
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__interactivehook__', '__loade
r__', '__name__', '__package__', '__spec__', '__stderr__', '__stdin__', '__stdou
t__', '_clear_type_cache', '_current_frames', '_debugmallocstats', '_enablelegac
ywindowsfsencoding', '_getframe', '_home', '_mercurial', '_xoptions', 'api_versi
on', 'argv', 'base_exec_prefix', 'base_prefix', 'builtin_module_names', 'byteord
er', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'dont
_write_bytecode', 'exc_info', 'excepthook', 'exec_prefix', 'executable', 'exit',
... 省略 ...
]
>>>
  • 内置函数 dir(object) 用于列出对象 object 中的属性
  • import sys 引入模块 sys
  • dir(sys) 列出模块 sys 定义的属性名、函数名、类名

1.2 获取对象的帮助文档

>>> help(max)
Help on built-in function max in module builtins:

max(...)
    max(iterable, *[, default=obj, key=func]) -> value
    max(arg1, arg2, *args, *[, key=func]) -> value

    With a single iterable argument, return its biggest item.    
  • help 命令用于获取指定对象的帮助
  • help(max) 获取内置函数 max 的帮助
>>> import sys
>>> help(sys.exit)
Help on built-in function exit in module sys:

exit(...)
    exit([status])

    Exit the interpreter by raising SystemExit(status).
    If the status is omitted or None, it defaults to zero (i.e., success).
    If the status is an integer, it will be used as the system exit status.
    If it is another kind of object, it will be printed and the system
    exit status will be one (i.e., failure).
  • help(sys.exit) 获取模块 sys 的函数 exit 的帮助

2. 文件 IO

2.1 读取用户输入

>>> line = input()
abc
>>> line
'abc'
  • 内置函数 input() 用于读取用户输入的一行文本
  • input() 读取用户输入的一行文本
>>> line = input('Input a number: ')
Input a number: 123
>>> line
'123'
  • input('Input a number: ') 首先打印提示符 'Input a number: ',然后再读取用户输入

2.2 打印输出

>>> print('hello')
hello
>>> print('hello', 'world')
hello world
  • 内置函数 print 打印文本到屏幕
  • 缺省情况下,print() 输出会加上换行

如果不需要换行,可以加上参数 end =’’,示例如下:

print('a', end = '')
print('b', end = '')
print('c', end = '')
print()

运行程序,输出结果:

abc

2.3 打开文件

>>> file = open('test.txt')
>>> file.readline()
the first line
  • 函数 open(path) 打开指定路径 path 的文件
  • 调用 file 对象的 readline() 方法返回一行

3. 类型转换

3.1 将字符串转换为整数

>>> number = int('123')
>>> number
123
  • 函数 int(string) 将字符串 string 转换为整数

3.2 将字符串转换为浮点数

>>> number = float('123.456')
>>> number
123.456
  • 函数 float(string) 将字符串 string 转换为浮点数

3.2 将数值转换为字符串

>>> string = str(123)
>>> string
'123'
>>> string = str(123.456)
>>> string
'123.456'
  • 函数 str(number) 将数值转换为字符串
  • str(123) 将整数转换为字符串
  • str(123.456) 将浮点数转换为字符串

4. 数学运算

>>> abs(-1)
1
>>> round(1.4)
1
>>> round(1.5)
2
  • abs(number) 计算 number 的绝对值
  • round(number) 进行四舍五入运算
>>> min(1, 2)
1
>>> max(1, 2)
2
>>> min(1, 2, 3)
1
>>> max(1, 2, 3)
3
  • min() 计算输入参数的最小值
  • max() 计算输入参数的最大值
>>> pow(2, 1)
2
>>> pow(2, 2)
4
>>> pow(2, 3)
8
  • pow(n, m) 计算 n 的 m 次方运算

5. 创建复合数据类型

Python 中的复合数据类型包括:

  • 列表
    • 提供了内置函数 list() 创建列表
  • 元组
    • 提供了内置函数 tuple() 创建元组
  • 字典
    • 提供了内置函数 dict() 创建字典
  • 集合
    • 提供了内置函数 set() 创建集合

5.1 创建列表

>>> x = list()
>>> x
[]
  • 创建一个空的列表
>>> iterable = ('a', 'b', 'c')
>>> x = list(iterable)
>>> x
['a', 'b', 'c']
  • 创建一个可迭代对象 iterable,iterable 是一个包含 3 个元素的元组
  • 通过 list(iterable) 将可迭代对象 iterable 转换为 list

5.2 创建元组

>>> x = tuple()
>>> x
()
  • 创建一个空的元组
>>> iterable = ['a', 'b', 'c']
>>> x = tuple(iterable)
>>> x
('a', 'b', 'c')
  • 创建一个可迭代对象 iterable,iterable 是一个包含 3 个元素的列表
  • 通过 tuple(iterable) 将可迭代对象 iterable 转换为 tuple

5.3 创建字典

>>> dict()
{}
  • 创建一个空的字典
>>> dict(a='A', b='B', c='C')
{'a': 'A', 'b': 'B', 'c': 'C'}
  • 通过命名参数创建包含 3 个键值对的字典
>>> pairs = [('a', 'A'), ('b', 'B'), ('c', 'C')]
>>> dict(pairs)
{'a': 'A', 'b': 'B', 'c': 'C'}
>>>
  • 定义列表 pairs
    • 由 3 个元组构成
    • 每个元组包含两项:键和值
  • 列表 pairs 包含了 3 个键值对
  • 创建一个包含 3 个键值对的字典

5.4 创建集合

>>> x = set()
>>> x
{}
  • 创建一个空的集合
>>> iterable = ('a', 'b', 'c')
>>> x = list(iterable)
>>> x
{'a', 'b', 'c'}
  • 创建一个可迭代对象 iterable,iterable 是一个包含 3 个元素的元组
  • 通过 set(iterable) 将可迭代对象 iterable 转换为 set

6. 对序列的操作

6.1 计算序列的长度

>>> len([1, 2, 3])
3
>>> len((1, 2, 3))
3
>>> len({1, 2, 3})
  • 计算列表 [1, 2, 3] 的长度,即列表中元素的数量
  • 计算元组 (1, 2, 3) 的长度,即元组中元素的数量
  • 计算集合 {1, 2, 3} 中元素的数量

6.2 对序列排序

>>> sorted([3, 1, 2])
[1, 2, 3]
>>> sorted([3, 1, 2], reverse=True)
[3, 2, 1]
  • 在第 1 行,返回按递增排序的队列
  • 在第 3 行,指定命名参数 reverse = True,返回递减增排序的队列

6.3 对序列倒置

reversed(seq) 函数返回一个倒置的迭代器,参数 seq 是一个序列可以是 tuple 或者 list。

>>> t = ('www', 'imooc', 'com')
>>> tuple(reversed(t))
('com', 'imooc', 'www')
>>> l = ['www', 'imooc', 'com']
>>> list(reversed(t))
['com', 'imooc', 'www']
  • 对元组中元素倒置
    • t 是一个元组
    • reversed(t) 返回一个倒置的迭代器
    • tuple(reversed(t)) 将迭代器转换为元组
  • 对列表中元素倒置
    • l 是一个元组
    • reversed(l) 返回一个倒置的迭代器
    • list(reversed(l)) 将迭代器转换为列表

7. 面向对象相关

Python 提供了如下内置函数用于判断类型:

函数 功能
isinstance(object, type) 判断 object 是否是类型 type 的实例
issubclass(a, b) 判断类型 a 是否是类型 b 的子类型

创建父类 Animal,继承于类 Animal 的两个子类 Human 和 Dog,代码如下:

class Animal:
    def __init__(self, name, age):
        self.name = name
        self.age = age

class Human(Animal):
    def __init__(self, name, age):
        pass

class Dog(Animal):
    def __init__(self, name, age):
        pass

tom = Human('tom', 30)         
  • 创建父类 Animal
  • 创建类 Human,继承于类 Animal,类 Human 是类 Animal 的子类
  • 创建类 Dog,继承于类 Animal,类 Dog 是类 Animal 的子类
  • 用类 Human 创建一个实例变量 tom
print('isinstance(tom, Animal) =', isinstance(tom, Animal))
print('isinstance(tom, Human) =', isinstance(tom, Human))
print('isinstance(tom, Dog) =', isinstance(tom, Dog))

print('issubclass(Dog, Animal) = ', issubclass(Dog, Animal))
print('issubclass(Dog, Human) = ', issubclass(Dog, Human))

运行程序,输出结果如下:

isinstance(tom, Animal) = True
isinstance(tom, Human) = True
isinstance(tom, Dog) = False
issubclass(Dog, Animal) =  True
issubclass(Dog, Human) =  False
  • tom 是一个 Animal
  • tom 是一个 Human
  • tom 不是 Dog
  • Dog 是 Animal 的子类型
  • Dog 不是 Human 的子类型