Python 装饰器(Decorators)是 Python 中一个非常有用的特性,它允许程序员扩展或修改函数或方法的行为,而无需修改其定义。以下是一些关于 Python 装饰器的基础知识和用法。
装饰器简介
装饰器是一个接受函数作为参数并返回一个新函数的函数。它主要用于在运行时修改函数的行为。
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
在上面的例子中,my_decorator
是一个装饰器,它接受 say_hello
函数作为参数,并返回一个新的函数 wrapper
。当调用 say_hello()
时,实际上调用的是 wrapper()
,因此会先执行装饰器中的代码。
常用装饰器
@staticmethod
和@classmethod
: 这些装饰器用于定义静态方法和类方法。@property
: 用于将方法转换为属性,以便可以通过属性访问方法。@functools.wraps
: 这个装饰器用于保留原始函数的元信息。
实战案例
假设我们有一个简单的登录系统,我们可以使用装饰器来确保只有登录用户才能访问某些功能。
def login_required(func):
def wrapper(*args, **kwargs):
if not user_is_logged_in():
print("You must be logged in to access this feature.")
return
return func(*args, **kwargs)
return wrapper
@login_required
def secret_page():
print("Welcome to the secret page!")
secret_page()
在这个例子中,login_required
是一个装饰器,它确保只有登录用户才能访问 secret_page
函数。
扩展阅读
更多关于 Python 装饰器的信息,您可以阅读 官方文档。
Python 装饰器示例