引言
Python 内置函数是语言核心功能的直接体现,掌握它们能显著提升代码效率和可读性。本文系统梳理 30 个最常用的内置函数,涵盖数据类型操作、函数式编程、输入输出、元编程等核心领域。每个函数均包含语法解析、参数说明、典型案例及注意事项,助力开发者写出更 Pythonic 的代码。
基础数据类型操作
1. len()
语法:len(iterable)
功能:返回对象长度或元素个数
案例:
print(len("Hello World"))
data = [1, 2, [3, 4]]
print(len(data))
stats = {"a": 1, "b": 2}
print(len(stats))
2. range()
语法:range(start, stop[, step])
功能:生成整数序列
案例:
for i in range(5):
print(i)
even_numbers = list(range(0, 10, 2))
3. enumerate()
语法:enumerate(iterable, start=0)
功能:同时获取索引和值
案例:
fruits = ["apple", "banana", "cherry"]
for index, value in enumerate(fruits, 1):
print(f"{index}: {value}")
4. zip()
语法:zip(*iterables)
功能:合并多个可迭代对象
案例:
names = ["Alice", "Bob"]
ages = [25, 30]
for name, age in zip(names, ages):
print(f"{name} is {age} years old")
5. sorted()
语法:sorted(iterable, key=None, reverse=False)
功能:返回排序后的新列表
案例:
words = ["apple", "banana", "cherry"]
sorted_words = sorted(words, key=len)
print(sorted_words)
函数式编程工具
6. map()
语法:map(function, iterable)
功能:对可迭代对象每个元素应用函数
案例:
numbers = [1, 2, 3, 4]
squares = list(map(lambda x: x**2, numbers))
print(squares)
7. filter()
语法:filter(function, iterable)
功能:筛选符合条件的元素
案例:
numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)
8. reduce()
语法:reduce(function, iterable[, initializer])
功能:对可迭代对象中的元素进行累积计算
案例:
from functools import reduce
numbers = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, numbers)
print(product)
9. any()
语法:any(iterable)
功能:检查是否至少有一个元素为真
案例:
permissions = ["read", "write"]
if any(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"}
if all(form_data.values()):
print("Form is valid")
else:
print("Missing fields")
输入输出与文件操作
11. open()
语法:open(file, mode='r', encoding=None)
功能:文件操作
案例:
with open("data.txt", "w", encoding="utf-8") as f:
f.write("Hello, World!")
with open("data.txt", "r", encoding="utf-8") as f:
content = f.read()
print(content)
12. print()
语法:print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
功能:输出内容到控制台
案例:
name = "Alice"
age = 25
print(f"Name: {name}, Age: {age}")
with open("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)
15. eval()
语法:eval(expression[, globals[, locals]])
功能:执行表达式并返回结果
案例:
result = eval("2 + 3 * 4")
print(result)
class_name = "int"
obj = eval(f"{class_name}(10)")
print(obj)
元编程与高级功能
16. dir()
语法:dir([object])
功能:查看对象属性和方法
案例:
print(dir([]))
import math
print(dir(math))
17. help()
语法:help([object])
功能:获取帮助文档
案例:
help(len)
help(list)
18. type()
语法:type(object)
功能:获取对象类型
案例:
print(type(10))
print(type("hello"))
print(type([1, 2, 3]))
19. isinstance()
语法:isinstance(object, classinfo)
功能:检查对象是否为指定类型
案例:
class MyClass:
pass
obj = MyClass()
print(isinstance(obj, MyClass))
print(isinstance(10, int))
20. hasattr()
语法:hasattr(object, name)
功能:检查对象是否有指定属性
案例:
class Person:
def __init__(self, name):
self.name = name
p = Person("Alice")
print(hasattr(p, "name"))
print(hasattr(p, "age"))
21. getattr()
语法:getattr(object, name[, default])
功能:获取对象属性值
案例:
class Config:
debug = False
config = Config()
print(getattr(config, "debug"))
print(getattr(config, "timeout", 30))
22. setattr()
语法:setattr(object, name, value)
功能:设置对象属性值
案例:
class User:
pass
user = User()
setattr(user, "name", "Alice")
setattr(user, "age", 25)
print(user.name, user.age)
23. delattr()
语法:delattr(object, name)
功能:删除对象属性
案例:
class Data:
value = 42
data = Data()
delattr(data, "value")
print(hasattr(data, "value"))
24. globals()
语法:globals()
功能:返回当前全局符号表
案例:
print(globals()["__name__"])
globals()["new_var"] = "Hello"
print(new_var)
25. locals()
语法:locals()
功能:返回当前局部符号表
案例:
def example():
local_var = 42
print(locals())
example()
26. vars()
语法:vars([object])
功能:返回对象属性字典
案例:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(1, 2)
print(vars(p))
27. callable()
语法:callable(object)
功能:检查对象是否可调用
案例:
print(callable(len))
print(callable(10))
print(callable(lambda x: x))
28. compile()
语法:compile(source, filename, mode)
功能:将源代码编译为代码对象
案例:
code_str = "print('Hello from compiled code')"
code_obj = compile(code_str, "<string>", "exec")
exec(code_obj)
29. id()
语法:id(object)
功能:返回对象的内存地址
案例:
a = 10
b = a
print(id(a))
print(id(b))
30. hash()
语法:hash(object)
功能:返回对象的哈希值
案例:
print(hash("hello"))
print(hash(10))
总结
Python 内置函数是语言核心竞争力的体现,合理使用能显著提升开发效率。建议掌握以下原则:
- 优先使用内置函数:如用
len() 代替手动计数,用 zip() 代替手动索引对齐
- 注意函数副作用:如
sorted() 返回新列表,而 list.sort() 原地排序
- 结合高级特性:将
map() 与生成器表达式结合,filter() 与 lambda 结合使用
- 避免过度使用:如
exec() 和 eval() 存在安全风险,需谨慎处理输入
通过系统掌握这些内置函数,开发者能写出更简洁、高效、Pythonic 的代码。建议结合官方文档持续学习,探索更多高级用法。