发布于2026-07-21 阅读(0)
扫一扫,手机访问
Python 的多范式特性是它的一大亮点——除了我们熟悉的面向对象和过程式编程,还藏着不少高阶玩法,比如函数式编程、装饰器、元类、生成器、协程等。掌握这些技巧,能让你的代码更简洁、更灵活,也更容易维护。下面就来逐一拆解这些核心概念。
在 Python 里,函数可以像普通变量一样被传递、赋值、作为参数或返回值。这种特性是很多高阶玩法的基础。
def greet(name):
return f"Hello, {name}"
def call_func(func, arg):
return func(arg)
print(call_func(greet, "Alice")) # 输出: Hello, Alice
高阶函数就是接受函数作为参数,或者返回一个函数的函数。Python 内置了好几个这样的“聪明”函数。
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
闭包可以理解为“带着记忆的函数”——它捕获了外层作用域中的变量,并在后续调用中继续使用。这在封装状态时非常有用。
def outer():
count = 0
def inner():
nonlocal count
count += 1
return count
return inner
counter = outer()
print(counter()) # 1
print(counter()) # 2
装饰器是 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!
元类是“类的类”,它控制着类的创建过程。通常用于自动注入属性、方法,或者做类注册——比如 ORM 框架中的模型定义就是靠元类实现的。
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
生成器是一种特殊的迭代器,它按需生成数据,而不是一次性生成所有结果,内存占用非常友好。核心关键字是 yield。
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)
异步 I/O 是 Python 处理高并发网络请求、IO 密集型任务的利器。通过 async 和 await,可以在单线程内实现高效的并发。
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())
描述符实现了 __get__、__set__、__delete__ 协议,可以自定义属性的访问逻辑。很多底层机制(比如 @property、@classmethod)的背后都是描述符。
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__
Python 的类可以通过重写 __init__、__str__、__repr__、__call__、__enter__、__exit__ 等方法,让对象的行为更自然——比如支持 with 语句、支持打印输出等。
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)
class RegularClass:
pass
class SlotsClass:
__slots__ = ['x', 'y']
def __init__(self, x, y):
self.x = x
self.y = y
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]
| 技术 | 用途 |
|---|---|
| 闭包 | 封装状态和逻辑 |
| 装饰器 | 增强函数行为 |
| 元类 | 控制类的创建逻辑 |
| 生成器 | 按需生成数据 |
| 异步编程 | 提升 IO 并发性能 |
| 描述符 | 自定义属性访问逻辑 |
| 魔术方法 | 实现自定义类型行为 |
这些高阶技巧能让你的 Python 代码更高效、更灵活、也更易于维护。掌握它们,你就能更好地发挥 Python 的全部潜力。
上一篇:【编程随想】编程思想
下一篇:趣味编程:少儿编程思维的启蒙之旅
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
8