Python中装饰器基础入门教程 Python中装饰器使用场景(装饰,场景,入门教程,基础,Python.......)

feifei123 发布于 2025-08-26 阅读(1)
Python装饰器通过封装函数增强功能,实现日志记录、权限校验、性能监控等横切关注点的分离。

python中装饰器基础入门教程 python中装饰器使用场景

Python装饰器本质上就是一个函数,它能接收一个函数作为参数,并返回一个新的函数。这个新函数通常在不修改原有函数代码的基础上,为其添加额外的功能或行为。它让我们的代码更模块化、可复用,并且更“优雅”地实现功能的增强或修改。它在很多场景下都能提升代码的可读性和可维护性,比如日志记录、性能监控、权限校验、缓存等。

解决方案

Okay, 咱们来聊聊Python装饰器这玩意儿。初次接触,很多人可能会觉得它有点“魔法”,但其实剥开来看,它就是函数式编程里一个很实用的概念。

简单来说,装饰器就是用来“包裹”另一个函数的。想象一下,你有一个函数,它能完成某个核心任务。但现在,你想在它执行前或执行后,或者在它执行过程中,加点额外的逻辑,比如记录日志、检查权限、计算执行时间等等。如果直接修改原函数,可能会让它变得臃肿,也破坏了它的单一职责。这时候,装饰器就派上用场了。

它的核心思想是:函数作为对象闭包

函数作为对象: 在Python里,函数和字符串、数字一样,都是一等公民。你可以把它赋值给变量,可以作为参数传给另一个函数,也可以作为另一个函数的返回值。这是理解装饰器的基石。

def greet(name):
    return f"Hello, {name}!"

my_func = greet # 将函数赋值给变量
print(my_func("Alice")) # Hello, Alice!

闭包: 闭包是指一个函数定义在一个内部函数中,并且内部函数引用了外部函数作用域中的变量,即使外部函数已经执行完毕,内部函数仍然可以访问和操作这些变量。

def outer_function(msg):
    def inner_function():
        print(msg)
    return inner_function

closure_instance = outer_function("Hello from closure!")
closure_instance() # Hello from closure!

把这两个概念结合起来,装饰器的基本形态就出来了:

def simple_decorator(func):
    def wrapper(*args, **kwargs):
        print("Something is happening before the function is called.")
        result = func(*args, **kwargs)
        print("Something is happening after the function is called.")
        return result
    return wrapper

@simple_decorator
def say_hello():
    print("Hello!")

@simple_decorator
def add(a, b):
    print(f"Adding {a} and {b}")
    return a + b

say_hello()
# Output:
# Something is happening before the function is called.
# Hello!
# Something is happening after the function is called.

print(add(3, 5))
# Output:
# Something is happening before the function is called.
# Adding 3 and 5
# Something is happening after the function is called.
# 8

这里的

@simple_decorator
语法糖,其实就是
say_hello = simple_decorator(say_hello)
的简写。它把
say_hello
函数传给了
simple_decorator
,然后
simple_decorator
返回的
wrapper
函数替换了原来的
say_hello

需要注意的是,

wrapper
函数的签名通常会使用
*args
**kwargs
来确保它能接受任何参数,这样被装饰的函数无论接受什么参数,装饰器都能正确地处理。

一个常见的坑是,装饰器会改变被装饰函数的元信息(比如

__name__
,
__doc__
)。为了保留这些信息,我们通常会使用
functools.wraps

import functools

def another_decorator(func):
    @functools.wraps(func) # 这一行很关键
    def wrapper(*args, **kwargs):
        print(f"Calling function: {func.__name__}")
        return func(*args, **kwargs)
    return wrapper

@another_decorator
def my_function_with_docstring(x, y):
    """This is a test function."""
    return x * y

print(my_function_with_docstring.__name__) # my_function_with_docstring (如果没有 @functools.wraps 会是 wrapper)
print(my_function_with_docstring.__doc__)  # This is a test function.

Python装饰器在实际开发中究竟能解决哪些痛点?

在实际开发中,装饰器简直是代码组织和功能增强的利器。我个人觉得,它最核心的价值在于关注点分离。很多时候,我们会有一些横切关注点(cross-cutting concerns),比如日志记录、性能监控、权限校验、缓存等,这些功能会分散在程序的各个角落。如果每次都手动添加,代码会变得重复且难以维护。装饰器就提供了一种优雅的方式来处理这些。

举几个例子:

  • 日志记录 (Logging): 这是最常见的场景之一。你想知道某个函数何时被调用,传入了什么参数,返回了什么结果。与其在每个函数内部都写一堆

    print
    logging.info
    ,不如用一个装饰器搞定。

    import logging
    import functools
    
    logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
    
    def log_calls(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            args_repr = [repr(a) for a in args]
            kwargs_repr = [f"{k}={v!r}" for k, v in kwargs.items()]
            signature = ", ".join(args_repr + kwargs_repr)
            logging.info(f"Calling {func.__name__}({signature})")
            result = func(*args, **kwargs)
            logging.info(f"{func.__name__} returned {result!r}")
            return result
        return wrapper
    
    @log_calls
    def divide(a, b):
        return a / b
    
    divide(10, 2)
    # 假设这里会抛出ZeroDivisionError,但日志依然会记录调用信息
    # divide(10, b=0)

    你看,

    divide
    函数本身只关心除法逻辑,日志记录的“脏活累活”都交给装饰器了。

  • 权限校验 (Authentication/Authorization): 在Web框架中尤其常见。某个视图函数只能让登录用户访问,或者只有管理员才能执行某个操作。

    import functools
    
    def requires_login(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            # 假设这里有一个检查用户是否登录的逻辑
            is_logged_in = False # 模拟未登录
            # is_logged_in = True # 模拟已登录
    
            if not is_logged_in:
                print("Error: You must be logged in to access this page.")
                # 在Web框架中,这里可能会重定向到登录页或返回401错误
                return None
            return func(*args, **kwargs)
        return wrapper
    
    @requires_login
    def view_secret_page(user_id):
        print(f"User {user_id} is viewing the secret page.")
        return "Secret content!"
    
    view_secret_page(123) # 未登录,会打印错误信息

    这比在每个需要权限的函数开头都写一遍

    if not current_user.is_authenticated(): ...
    要干净得多。

如何利用装饰器实现性能监控和

以上就是Python中装饰器基础入门教程 Python中装饰器使用场景的详细内容,更多请关注资源网其它相关文章!

标签:  python access win 作用域 asic Python print if 封装 Logging 字符串  闭包 对象 

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。