Python(32)Python内置函数全解析:30个核心函数的语法、案例与最佳实践
目录

引言
Python内置函数是语言核心功能的直接体现,掌握它们能显著提升代码效率和可读性。本文系统梳理30个最常用的内置函数,涵盖数据类型操作、函数式编程、输入输出、元编程等核心领域。每个函数均包含语法解析、参数说明、典型案例及注意事项,助力开发者写出更Pythonic的代码。
基础数据类型操作
1. len()
语法:len(iterable)
功能:返回对象长度或元素个数
案例:
# 字符串长度print(len("Hello World"))# 11# 列表元素个数 data =[1,2,[3,4]]print(len(data))# 3# 字典键值对数量 stats ={"a":1,"b":2}print(len(stats))# 22. range()
语法:range(start, stop[, step])
功能:生成整数序列
案例:
# 生成0-4序列for i inrange(5):print(i)# 0,1,2,3,4# 步长为2 even_numbers =list(range(0,10,2))# [0,2,4,6,8]3. enumerate()
语法:enumerate(iterable, start=0)
功能:同时获取索引和值
案例:
fruits =["apple","banana","cherry"]for index, value inenumerate(fruits,1):print(f"{index}: {value}")# 1: apple# 2: banana# 3: cherry4. zip()
语法:zip(*iterables)
功能:合并多个可迭代对象
案例:
names =["Alice","Bob"] ages =[25,30]for name, age inzip(names, ages):print(f"{name} is {age} years old")# Alice is 25 years old# Bob is 30 years old5. sorted()
语法:sorted(iterable, key=None, reverse=False)
功能:返回排序后的新列表
案例:
# 按字符串长度排序 words =["apple","banana","cherry"] sorted_words =sorted(words, key=len)print(sorted_words)# ['apple', 'cherry', 'banana']函数式编程工具
6. map()
语法:map(function, iterable)
功能:对可迭代对象每个元素应用函数
案例:
# 平方计算 numbers =[1,2,3,4] squares =list(map(lambda x: x**2, numbers))print(squares)# [1, 4, 9, 16]7. filter()
语法:filter(function, iterable)
功能:筛选符合条件的元素
案例:
# 过滤偶数 numbers =[1,2,3,4,5,6] evens =list(filter(lambda x: x %2==0, numbers))print(evens)# [2, 4, 6]8. reduce()
语法:reduce(function, iterable[, initializer])
功能:对可迭代对象中的元素进行累积计算
案例:
from functools importreduce# 计算乘积 numbers =[1,2,3,4] product =reduce(lambda x, y: x * y, numbers)print(product)# 249. any()
语法:any(iterable)
功能:检查是否至少有一个元素为真
案例:
# 检测用户权限 permissions =["read","write"]ifany(perm in permissions for perm in["delete","execute"]):print("Has required permission")else:print("Permission denied")# 输出10. all()
语法:all(iterable)
功能:检查是否所有元素都为真
案例:
# 验证表单数据 form_data ={"username":"alice","email":"[email protected]","age":"25"}ifall(form_data.values()):print("Form is valid")else:print("Missing fields")输入输出与文件操作
11. open()
语法:open(file, mode='r', encoding=None)
功能:文件操作
案例:
# 写入文件withopen("data.txt","w", encoding="utf-8")as f: f.write("Hello, World!")# 读取文件withopen("data.txt","r", encoding="utf-8")as f: content = f.read()print(content)# Hello, World!12. print()
语法:print(*objects,, end='\n', file=sys.stdout)
功能:输出内容到控制台
案例:
# 格式化输出 name ="Alice" age =25print(f"Name: {name}, Age: {age}")# Name: Alice, Age: 25# 重定向输出到文件withopen("output.txt","w")as f:print("This will be written to file",file=f)13. input()
语法:input([prompt])
功能:获取用户输入
案例:
# 简单交互 username =input("Enter your name: ")print(f"Welcome, {username}!")14. exec()
语法:exec(object[, globals[, locals]])
功能:执行动态生成的代码
案例:
# 动态执行代码 code =""" def greet(name): print(f"Hello, {name}!") greet("Bob") """exec(code)# 输出: Hello, Bob!15. eval()
语法:eval(expression[, globals[, locals]])
功能:执行表达式并返回结果
案例:
# 计算数学表达式 result =eval("2 + 3 * 4")print(result)# 14# 动态创建对象 cls_name ="int" obj =eval(f"{cls_name}(10)")print(obj)# 10元编程与高级功能
16. dir()
语法:dir([object])
功能:查看对象属性和方法
案例:
# 查看列表方法print(dir([]))# 包含append, count, index等方法# 查看模块内容import math print(dir(math))# 包含sqrt, pi等属性和函数17. help()
语法:help([object])
功能:获取帮助文档
案例:
# 查看len函数的帮助help(len)# 查看列表的帮助help(list)18. type()
语法:type(object)
功能:获取对象类型
案例:
# 类型检查print(type(10))# <class 'int'>print(type("hello"))# <class 'str'>print(type([1,2,3]))# <class 'list'>19. isinstance()
语法:isinstance(object, classinfo)
功能:检查对象是否为指定类型
案例:
# 类型验证classMyClass:pass obj = MyClass()print(isinstance(obj, MyClass))# Trueprint(isinstance(10,int))# True20. hasattr()
语法:hasattr(object, name)
功能:检查对象是否有指定属性
案例:
classPerson:def__init__(self, name): self.name = name p = Person("Alice")print(hasattr(p,"name"))# Trueprint(hasattr(p,"age"))# False21. getattr()
语法:getattr(object, name[, default])
功能:获取对象属性值
案例:
classConfig: debug =False config = Config()print(getattr(config,"debug"))# Falseprint(getattr(config,"timeout",30))# 30(属性不存在时返回默认值)22. setattr()
语法:setattr(object, name, value)
功能:设置对象属性值
案例:
classUser:pass user = User()setattr(user,"name","Alice")setattr(user,"age",25)print(user.name, user.age)# Alice 2523. delattr()
语法:delattr(object, name)
功能:删除对象属性
案例:
classData: value =42 data = Data()delattr(data,"value")print(hasattr(data,"value"))# False24. globals()
语法:globals()
功能:返回当前全局符号表
案例:
# 查看全局变量print(globals()["__name__"])# __main__# 动态创建全局变量globals()["new_var"]="Hello"print(new_var)# Hello25. locals()
语法:locals()
功能:返回当前局部符号表
案例:
defexample(): local_var =42print(locals()) example()# 输出包含'local_var'的字典26. vars()
语法:vars([object])
功能:返回对象属性字典
案例:
classPoint:def__init__(self, x, y): self.x = x self.y = y p = Point(1,2)print(vars(p))# {'x': 1, 'y': 2}27. callable()
语法:callable(object)
功能:检查对象是否可调用
案例:
print(callable(len))# True(函数对象)print(callable(10))# False(整数不可调用)print(callable(lambda x: x))# True(lambda表达式)28. compile()
语法:compile(source, filename, mode)
功能:将源代码编译为代码对象
案例:
# 编译并执行代码 code_str ="print('Hello from compiled code')" code_obj =compile(code_str,"<string>","exec")exec(code_obj)# 输出: Hello from compiled code29. id()
语法:id(object)
功能:返回对象的内存地址
案例:
a =10 b = a print(id(a))# 140735530235488print(id(b))# 140735530235488(相同值对象共享内存)30. hash()
语法:hash(object)
功能:返回对象的哈希值
案例:
print(hash("hello"))# -7176065445015297706print(hash(10))# 10总结
Python内置函数是语言核心竞争力的体现,合理使用能显著提升开发效率。建议掌握以下原则:
- 优先使用内置函数:如用
len()代替手动计数,用zip()代替手动索引对齐 - 注意函数副作用:如
sorted()返回新列表,而list.sort()原地排序 - 结合高级特性:将
map()与生成器表达式结合,filter()与lambda结合使用 - 避免过度使用:如
exec()和eval()存在安全风险,需谨慎处理输入
通过系统掌握这些内置函数,开发者能写出更简洁、高效、Pythonic的代码。建议结合官方文档持续学习,探索更多高级用法。