Python内置函数详解
文章目录
- 什么是Python内置函数?
- 内置函数分类详解
- 1. 数学运算类
- abs(x)
- divmod(a, b)
- pow(x, y[, z])
- round(number[, ndigits])
- 2. 类型转换类
- int(x[, base])
- float(x)
- str(object)
- bool(x)
- 3. 序列操作类
- len(s)
- range(start, stop[, step])
- sorted(iterable[, key][, reverse])
- reversed(seq)
- 4. 迭代器和生成器类
- iter(object[, sentinel])
- next(iterator[, default])
- 5. 对象操作类
- type(object)
- isinstance(object, classinfo)
- id(object)
- 6. 输入输出类
- print(*objects, sep=' ', end='\n')
- input([prompt])
- 7. 其他重要内置函数
- zip(*iterables)
- map(function, iterable, ...)
- filter(function, iterable)
- 8. 高级内置函数
- property(fget=None, fset=None, fdel=None, doc=None)
- staticmethod(function)
- classmethod(function)
- 9. 上下文管理器函数
- contextlib.contextmanager
- 性能优化建议
- Python版本差异
- Python 2 vs Python 3
- 实际开发中的注意事项
- 调试技巧
- 最佳实践示例
- 1. 数据处理优化
- 2. 文件操作最佳实践
- 3. 异常处理最佳实践
什么是Python内置函数?
Python内置函数是Python解释器中预定义的函数,无需导入任何模块即可直接使用。这些函数提供了Python编程中最基础和常用的功能,是Python语言的核心组成部分。
内置函数分类详解
1. 数学运算类
abs(x)
- 功能:返回数字的绝对值
- 参数:数字(整数/浮点数/复数)
- 示例:
print(abs(-5)) # 输出:5
print(abs(3.14)) # 输出:3.14
divmod(a, b)
- 功能:返回两个数的商和余数
- 参数:两个数字
- 示例:
print(divmod(7, 2)) # 输出:(3, 1)
pow(x, y[, z])
- 功能:返回x的y次方(如果提供z,则返回x的y次方对z取余)
- 示例:
print(pow(2, 3)) # 输出:8
print(pow(2, 3, 5)) # 输出:3
round(number[, ndigits])
- 功能:四舍五入到指定小数位
- 示例:
print(round(3.1415, 2)) # 输出:3.14
2. 类型转换类
int(x[, base])
- 功能:将对象转换为整数
- 示例:
print(int('123')) # 输出:123
print(int('1010', 2)) # 输出:10(二进制转十进制)
float(x)
- 功能:将对象转换为浮点数
- 示例:
print(float('3.14')) # 输出:3.14
str(object)
- 功能:将对象转换为字符串
- 示例:
print(str(123)) # 输出:'123'
bool(x)
- 功能:将对象转换为布尔值
- 示例:
print(bool(1)) # 输出:True
print(bool('')) # 输出:False
3. 序列操作类
len(s)
- 功能:返回对象的长度
- 示例:
print(len([1, 2, 3])) # 输出:3
print(len('Python')) # 输出:6
range(start, stop[, step])
- 功能:生成数字序列
- 示例:
for i in range(0, 5, 2):
print(i) # 输出:0, 2, 4
sorted(iterable[, key][, reverse])
- 功能:返回排序后的新列表
- 示例:
print(sorted([3, 1, 4, 1, 5])) # 输出:[1, 1, 3, 4, 5]
reversed(seq)
- 功能:返回反转的迭代器
- 示例:
print(list(reversed([1, 2, 3]))) # 输出:[3, 2, 1]
4. 迭代器和生成器类
iter(object[, sentinel])
- 功能:返回迭代器对象
- 示例:
it = iter([1, 2, 3])
print(next(it)) # 输出:1
next(iterator[, default])
- 功能:返回迭代器的下一个项目
- 示例:
it = iter([1, 2])
print(next(it)) # 输出:1
print(next(it)) # 输出:2
print(next(it, 'end')) # 输出:'end'
5. 对象操作类
type(object)
- 功能:返回对象的类型
- 示例:
print(type(123)) # 输出:<class 'int'>
isinstance(object, classinfo)
- 功能:判断对象是否是指定类型
- 示例:
print(isinstance(123, int)) # 输出:True
id(object)
- 功能:返回对象的唯一标识符
- 示例:
x = [1, 2, 3]
print(id(x)) # 输出:对象的内存地址
6. 输入输出类
print(*objects, sep=’ ‘, end=’\n’)
- 功能:打印输出
- 示例:
print('Hello', 'World', sep=', ') # 输出:Hello, World
input([prompt])
- 功能:接收用户输入
- 示例:
name = input('请输入你的名字:')
print(f'你好,{name}')
7. 其他重要内置函数
zip(*iterables)
- 功能:将多个可迭代对象打包成元组的迭代器
- 示例:
list(zip([1, 2], ['a', 'b'])) # 输出:[(1, 'a'), (2, 'b')]
map(function, iterable, …)
- 功能:对可迭代对象的每个元素应用函数
- 示例:
list(map(str, [1, 2, 3])) # 输出:['1', '2', '3']
filter(function, iterable)
- 功能:过滤可迭代对象中的元素
- 示例:
list(filter(lambda x: x > 0, [-1, 0, 1, 2])) # 输出:[1, 2]
8. 高级内置函数
property(fget=None, fset=None, fdel=None, doc=None)
- 功能:将方法转换为属性
- 应用场景:实现属性的getter和setter,提供更优雅的属性访问方式
- 示例:
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
if value < 0:
raise ValueError("半径不能为负数")
self._radius = value
staticmethod(function)
- 功能:将方法转换为静态方法
- 应用场景:定义不需要访问类或实例属性的方法
- 示例:
class MathUtils:
@staticmethod
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
classmethod(function)
- 功能:将方法转换为类方法
- 应用场景:实现替代构造函数,处理类级别的操作
- 示例:
class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
@classmethod
def from_string(cls, date_string):
year, month, day = map(int, date_string.split('-'))
return cls(year, month, day)
9. 上下文管理器函数
contextlib.contextmanager
- 功能:创建上下文管理器
- 应用场景:资源管理、临时状态修改
- 示例:
from contextlib import contextmanager
@contextmanager
def timer():
import time
start = time.time()
yield
end = time.time()
print(f"执行时间:{end - start}秒")
with timer():
# 执行某些操作
pass
性能优化建议
-
使用内置函数替代自定义实现
- 内置函数是用C语言实现的,性能通常优于Python实现
- 例如:使用
sum()
替代手动循环求和
-
合理使用生成器函数
- 对于大数据集,使用生成器可以减少内存使用
- 例如:使用
range()
替代list(range())
-
选择合适的数据结构
- 使用
set()
进行成员检测比list
更快 - 使用
dict.get()
替代try-except
进行键值获取
- 使用
Python版本差异
Python 2 vs Python 3
-
print 函数
- Python 2:print 是语句
- Python 3:print() 是函数
-
input 函数
- Python 2:raw_input() 获取字符串,input() 评估输入
- Python 3:input() 总是返回字符串
-
range 函数
- Python 2:range() 返回列表
- Python 3:range() 返回可迭代对象
实际开发中的注意事项
-
异常处理
- 使用
try-except
处理可能的类型转换错误 - 对输入参数进行有效性验证
- 使用
-
性能考虑
- 避免在循环中重复调用内置函数
- 使用性能分析工具评估性能瓶颈
-
代码可维护性
- 合理使用函数注释和类型提示
- 遵循Python的编码规范
-
安全性考虑
- 避免使用
eval()
处理不信任的输入 - 注意数据类型转换时的边界情况
- 避免使用
调试技巧
-
使用内置函数进行调试
- dir():查看对象的属性和方法
- vars():获取对象的__dict__属性
- locals():查看当前作用域的局部变量
-
使用断言进行测试
- assert语句配合内置函数验证假设
- 使用__debug__变量控制断言
最佳实践示例
1. 数据处理优化
# 低效的实现
data = [1, 2, 3, 4, 5]
result = 0
for num in data:
result += num
# 优化后的实现
result = sum(data)
2. 文件操作最佳实践
# 推荐使用上下文管理器
with open('file.txt', 'r') as f:
content = f.read()
# 而不是
f = open('file.txt', 'r')
try:
content = f.read()
finally:
f.close()
3. 异常处理最佳实践
# 推荐的方式
def safe_convert_to_int(value):
try:
return int(value)
except (ValueError, TypeError):
return None
# 而不是
def unsafe_convert_to_int(value):
return int(value) # 可能引发异常