Python 高阶编程
Python 是一门支持多种编程范式的语言,除了基本的面向对象和过程式编程外,它还提供了许多高阶编程技巧,包括函数式编程、装饰器、元类、生成器、协程等。这些特性可以帮助你写出更简洁、灵活、可维护的代码。
函数是一等公民(First-class Functions)
在 Python 中,函数可以像变量一样被传递、赋值、作为参数或返回值。
示例:
def greet(name):
return f"Hello, {name}"
def call_func(func, arg):
return func(arg)
print(call_func(greet, "Alice")) # 输出: Hello, Alice
高阶函数(Higher-order Functions)
高阶函数是指接受函数作为参数或返回一个函数的函数。
常见内置高阶函数:
map()
filter()
sorted()
functools.reduce()
示例:
from functools import reduce
nums = [1, 2, 3, 4, 5]
# map:对每个元素应用函数
squared = list(map(lambda x: x ** 2, nums)) # [1, 4, 9, 16, 25]
# filter:过滤符合条件的元素
even = list(filter(lambda x: x % 2 == 0, nums)) # [2, 4]
# reduce:累积计算
total = reduce(lambda x, y: x + y, nums) # 15
闭包(Closure)
闭包是指一个函数捕获了其作用域中的变量,并能够在其他上下文中继续使用这些变量。
示例:
def outer():
count = 0
def inner():
nonlocal count
count += 1
return count
return inner
counter = outer()
print(counter()) # 1
print(counter()) # 2
装饰器(Decorators)
装饰器是 Python 中最强大的功能之一,用于增强或修改函数行为而不修改其源码。
简单装饰器:
def my_decorator(func):
def wrapper(*args, **kwargs):
print("Before function call")
result = func(*args, **kwargs)
print("After function call")
return result
return wrapper
@my_decorator
def say_hello():
print("Hello")
say_hello()
输出:
Before function call
Hello
After function call
带参数的装饰器
可以定义装饰器本身也接受参数。
def repeat(times):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(3)
def greet(name):
print(f"Hello, {name}")
greet("Alice")
类装饰器
不仅可以装饰函数,还可以装饰类。
def add_method(cls):
def new_method(self):
return "New method added!"
cls.new_method = new_method
return cls
@add_method
class MyClass:
pass
obj = MyClass()
print(obj.new_method()) # 输出: New method added!
元类(Metaclass)
元类控制类的创建过程,是“类的类”。通常用于自动注入属性、方法或进行类注册等操作。
示例:自定义元类
class MyMeta(type):
def __new__(cls, name, bases, attrs):
if 'required_method' not in attrs:
raise TypeError("必须实现 required_method 方法")
return super().__new__(cls, name, bases, attrs)
class MyClass(metaclass=MyMeta):
def required_method(self):
pass
# 下面这行会报错,因为没有实现 required_method
# class BadClass(metaclass=MyMeta):
# pass
生成器(Generators)
生成器是一种特殊的迭代器,可以按需生成数据,节省内存。
使用 yield
定义生成器:
def fibonacci(n):
a, b = 0, 1
while a < n:
yield a
a, b = b, a + b
for num in fibonacci(100):
print(num)
协程与异步编程(async/await)
Python 支持异步 I/O 操作,适用于高并发网络请求、IO 密集型任务。
示例:
import asyncio
async def say_after(delay, what):
await asyncio.sleep(delay)
print(what)
async def main():
task1 = asyncio.create_task(say_after(1, "Hello"))
task2 = asyncio.create_task(say_after(2, "World"))
print("Started at", asyncio.get_event_loop().time())
await task1
await task2
print("Finished at", asyncio.get_event_loop().time())
asyncio.run(main())
描述符(Descriptors)
描述符是一个实现了特定协议的对象,可以自定义属性访问逻辑。
class RevealAccess:
def __init__(self, initval=None, name='var'):
self.val = initval
self.name = name
def __get__(self, instance, owner):
print('Getting', self.name)
return self.val
def __set__(self, instance, value):
print('Setting', self.name)
self.val = value
class MyClass:
x = RevealAccess(10, 'x')
m = MyClass()
print(m.x) # 触发 __get__
m.x = 20 # 触发 __set__
魔术方法(Magic Methods / Dunder Methods)
通过重写 __init__
, __str__
, __repr__
, __call__
, __enter__
, __exit__
等方法,可以让类具有更自然的行为。
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name} is {self.age} years old."
def __repr__(self):
return f"Person('{self.name}', {self.age})"
p = Person("Bob", 30)
print(p) # 输出: Bob is 30 years old.
print(repr(p)) # 输出: Person('Bob', 30)
上下文管理器
# 使用with语句
with open('file.txt', 'r') as f:
content = f.read()
# 自定义上下文管理器
class MyContextManager:
def __enter__(self):
print("Entering context")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("Exiting context")
with MyContextManager() as cm:
print("Inside context")
并发和多线程
from concurrent.futures import ThreadPoolExecutor
import time
def task(name):
print(f"Task {name} started")
time.sleep(2)
print(f"Task {name} finished")
return f"Result from {name}"
with ThreadPoolExecutor(max_workers=3) as executor:
results = executor.map(task, ['A', 'B', 'C'])
for result in results:
print(result)
性能优化技巧
使用__slots__
class RegularClass:
pass
class SlotsClass:
__slots__ = ['x', 'y']
def __init__(self, x, y):
self.x = x
self.y = y
使用functools.lru_cache缓存
from functools import lru_cache
@lru_cache(maxsize=None)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
设计模式实现
单例模式
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
工厂模式
class Dog:
def speak(self):
return "Woof!"
class Cat:
def speak(self):
return "Meow!"
def get_pet(pet="dog"):
pets = dict(dog=Dog(), cat=Cat())
return pets[pet]
总结:Python 高阶编程常用技术
技术 | 用途 |
---|---|
闭包 | 封装状态和逻辑 |
装饰器 | 增强函数行为 |
元类 | 控制类的创建逻辑 |
生成器 | 按需生成数据 |
异步编程 | 提升 IO 并发性能 |
描述符 | 自定义属性访问逻辑 |
魔术方法 | 实现自定义类型行为 |
这些高阶编程技术可以帮助你编写更高效、更灵活和更易于维护的Python代码。掌握这些概念将使你能够更好地利用Python的强大功能
推荐学习资源
- 《流畅的 Python》 —— Luciano Ramalho 著
- Python 官方文档 - Data model
- Real Python - Advanced Python
- Awesome Python 高阶技巧