Python 高阶编程:内置函数、异步任务与 30+ 核心技巧,一篇搞定!
摘要
本文系统梳理 Python 进阶阶段必须掌握的 5 大模块:内置函数、函数注解、异步函数、面向对象编程与魔法函数。全文包含 30 余个可独立运行的代码示例与多张对比表格,从“怎么用”讲到“为什么这样用”,帮你把零散知识点串成体系。无论是写工具脚本、Web 后端还是自动化测试,读完都能直接套用。
一句话核心卖点:掌握这 30+ 个技巧,你的 Python 代码会少写一半、快一倍、优雅十倍!
一、内置函数:事半功倍的瑞士军刀
Python 内置函数不需要 import 就能直接使用,熟练运用它们能让代码更短、更快、更具可读性。
1.1 类型转换与判断
| int() | 转整数 | int("42") → 42 |
| str() | 转字符串 | str(42) → "42" |
| list() | 转列表 | list("abc") → ['a', 'b', 'c'] |
| dict() | 转字典 | dict([('a', 1)]) → {'a': 1} |
| isinstance() | 类型判断 | isinstance(3, int) → True |
| callable() | 是否可调用 | callable(print) → True |
# 类型转换与判断示例
value = " 123 "
num = int(value.strip())
print(num, type(num)) # 123 <class 'int'>
data = [1, 2, 3]
print(isinstance(data, (list, tuple))) # True
1.2 序列与迭代工具
nums = [10, 20, 30]
# enumerate 同时拿到索引和值
for idx, val in enumerate(nums, start=1):
print(idx, val)
# 输出:
# 1 10
# 2 20
# 3 30
# zip 并行打包多个序列
names = ["a", "b", "c"]
scores = [90, 85, 88]
print(list(zip(names, scores)))
# [('a', 90), ('b', 85), ('c', 88)]
# zip 解压
pairs = [("x", 1), ("y", 2)]
ks, vs = zip(*pairs)
print(ks, vs) # ('x', 'y') (1, 2)
1.3 函数式编程三件套
from functools import reduce
nums = [1, 2, 3, 4, 5]
# map:对每个元素做转换
squares = list(map(lambda x: x ** 2, nums))
print(squares) # [1, 4, 9, 16, 25]
# filter:按条件过滤
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens) # [2, 4]
# reduce:累积计算
total = reduce(lambda acc, x: acc + x, nums)
print(total) # 15
1.4 对象内省与反射
class User:
def __init__(self, name: str):
self.name = name
u = User("Tom")
print(hasattr(u, "name")) # True
print(getattr(u, "name")) # Tom
setattr(u, "age", 20)
print(u.age) # 20
print(dir(u)[:3]) # ['__class__', '__delattr__', '__dict__'](前3个)
二、函数注解:让代码自带说明书
函数注解(Function Annotations)不会强制类型检查,但能让代码意图更清晰,并配合 mypy 做静态检查。
2.1 基础类型注解
def add(x: int, y: int) –> int:
return x + y
print(add(2, 3)) # 5
print(add.__annotations__)
# {'x': <class 'int'>, 'y': <class 'int'>, 'return': <class 'int'>}
2.2 复杂类型注解
from typing import Optional, Union, List, Dict, Callable
def describe_user(
name: str,
age: Optional[int] = None,
tags: List[str] = None,
scores: Dict[str, Union[int, float]] = None,
) –> str:
if tags is None:
tags = []
if scores is None:
scores = {}
return f"{name}: age={age}, tags={tags}, scores={scores}"
print(describe_user("Alice", age=25, tags=["vip"], scores={"math": 95.5}))
# Alice: age=25, tags=['vip'], scores={'math': 95.5}
2.3 Callable 与回调函数
from typing import Callable
def execute(x: int, func: Callable[[int], int]) –> int:
return func(x)
result = execute(5, lambda n: n * n)
print(result) # 25
三、异步函数:告别阻塞,性能翻倍
当程序需要等待网络、IO 或数据库响应时,异步能让 CPU 去做别的事,而不是空等。
3.1 async / await 核心语法
import asyncio
async def say_after(delay: int, message: str) –> None:
await asyncio.sleep(delay)
print(message)
async def main():
await say_after(1, "hello")
await say_after(2, "world")
asyncio.run(main())
# 耗时约 3 秒,顺序执行
3.2 并发执行多个任务
import asyncio
async def fetch(url: str) –> str:
await asyncio.sleep(1) # 模拟网络请求
return f"data from {url}"
async def main():
urls = ["a.com", "b.com", "c.com"]
tasks = [asyncio.create_task(fetch(u)) for u in urls]
results = await asyncio.gather(*tasks)
print(results)
# ['data from a.com', 'data from b.com', 'data from c.com']
asyncio.run(main())
# 3 个请求并发,耗时约 1 秒
3.3 异步迭代器与上下文管理器
import asyncio
from contextlib import asynccontextmanager
class AsyncCounter:
def __init__(self, limit: int):
self.limit = limit
self.current = 0
def __aiter__(self):
return self
async def __anext__(self):
if self.current >= self.limit:
raise StopAsyncIteration
await asyncio.sleep(0.1)
self.current += 1
return self.current
async def main():
async for num in AsyncCounter(3):
print(num)
# 输出:1 2 3(每行间隔 0.1 秒)
asyncio.run(main())
四、面向对象与魔法函数:写出 Pythonic 的类
4.1 类、继承与多态
class Animal:
def speak(self) –> str:
return "动物叫"
class Dog(Animal):
def speak(self) –> str:
return "汪汪"
class Cat(Animal):
def speak(self) –> str:
return "喵喵"
for animal in [Dog(), Cat()]:
print(animal.speak())
# 汪汪
# 喵喵
4.2 封装与 property
class Circle:
def __init__(self, radius: float):
self._radius = radius
@property
def radius(self) –> float:
return self._radius
@radius.setter
def radius(self, value: float):
if value <= 0:
raise ValueError("半径必须大于0")
self._radius = value
@property
def area(self) –> float:
return 3.14159 * self._radius ** 2
c = Circle(2)
print(c.area) # 12.56636
c.radius = 3
print(c.area) # 28.27431
4.3 常用魔法方法
class Vector:
def __init__(self, x: float, y: float):
self.x = x
self.y = y
def __str__(self) –> str:
return f"Vector({self.x}, {self.y})"
def __repr__(self) –> str:
return f"Vector(x={self.x}, y={self.y})"
def __len__(self) –> int:
return 2
def __add__(self, other: "Vector") –> "Vector":
return Vector(self.x + other.x, self.y + other.y)
def __eq__(self, other: object) –> bool:
if not isinstance(other, Vector):
return NotImplemented
return self.x == other.x and self.y == other.y
v1 = Vector(1, 2)
v2 = Vector(3, 4)
print(str(v1 + v2)) # Vector(4, 6)
print(repr(v1)) # Vector(x=1, y=2)
print(len(v1)) # 2
print(v1 == Vector(1, 2)) # True
4.4 可调用对象与上下文管理器
class Logger:
def __call__(self, message: str):
print(f"[LOG] {message}")
def __enter__(self):
print("开始记录")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("结束记录")
return False
log = Logger()
log("系统启动") # [LOG] 系统启动
with Logger() as logger:
logger("写入日志")
# 开始记录
# [LOG] 写入日志
# 结束记录
五、总结速查表
5.1 内置函数速查
| 类型转换 | int, str, list, dict, set, tuple |
| 迭代工具 | range, enumerate, zip, map, filter, sorted |
| 判断 | isinstance, callable, hasattr, all, any |
| 反射 | getattr, setattr, hasattr, dir |
5.2 魔法方法速查
| 初始化 | __init__ |
| 字符串表示 | __str__, __repr__ |
| 比较与运算 | __eq__, __add__, __len__ |
| 容器行为 | __getitem__, __setitem__, __iter__, __next__ |
| 可调用与上下文 | __call__, __enter__, __exit__ |
| 异步 | __aiter__, __anext__ |
5.3 异步关键字速查
| async def | 定义协程函数 |
| await | 等待协程完成 |
| asyncio.run() | 启动事件循环 |
| asyncio.create_task() | 创建后台任务 |
| asyncio.gather() | 并发等待多个任务 |
| async for | 异步迭代 |
| async with | 异步上下文管理 |
写在最后
把这 5 块内容练熟,Python 进阶就跨过了一道大坎。建议挑一个工作中的真实场景,比如批量请求接口、封装配置类、写日志上下文管理器,亲自动手重构一遍,印象会更深。
如果这篇文章对你有帮助,欢迎点赞、收藏、评论交流!你还想看 Python 哪个进阶主题?欢迎在评论区告诉我。




