商城首页欢迎来到中国正版软件门户

您的位置: 首页 > 文章列表 > 编程开发 > Python编程: 高阶编程

Python编程: 高阶编程

  发布于2026-07-21 阅读(0)

扫一扫,手机访问

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)

高阶函数就是接受函数作为参数,或者返回一个函数的函数。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

闭包(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)

元类是“类的类”,它控制着类的创建过程。通常用于自动注入属性、方法,或者做类注册——比如 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

生成器(Generators)

生成器是一种特殊的迭代器,它按需生成数据,而不是一次性生成所有结果,内存占用非常友好。核心关键字是 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)

协程与异步编程(async/await)

异步 I/O 是 Python 处理高并发网络请求、IO 密集型任务的利器。通过 asyncawait,可以在单线程内实现高效的并发。

示例:
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)

描述符实现了 __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__

魔术方法(Magic Methods / Dunder Methods)

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)

性能优化技巧

使用__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 高阶技巧
本文转载于:https://blog.csdn.net/waitingherefor/article/details/148832485 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。

热门关注