装饰器(Decorator)是 Python 中的一种高级功能,它允许我们在不修改原始函数的情况下,为其添加新的功能,装饰器本质上是一个 Python 函数,它接受一个函数作为参数,并返回一个新的函数。

1. 装饰器的定义
装饰器是一个接受函数作为参数并返回新函数的函数,在 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
2. 装饰器的使用
要使用装饰器,我们需要在定义函数时,使用 @ 符号将装饰器应用于函数。
@my_decorator
def say_hello():
print("Hello!")
在这个例子中,当我们调用 say_hello() 函数时,实际上是在调用 my_decorator(say_hello) 返回的新函数 wrapper()。
3. 装饰器的参数和返回值
装饰器可以接受任意数量的参数,这些参数将在原始函数被调用之前和之后执行,装饰器也可以有自己的返回值,这个返回值将被用作被装饰函数的返回值。
def my_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
在这个例子中,*args 和 **kwargs 允许装饰器处理任意数量的位置参数和关键字参数。
4. 装饰器的嵌套
我们可以在一个函数上应用多个装饰器,它们将按照从内到外的顺序执行。
def decorator1(func):
def wrapper():
print("Decorator 1")
func()
return wrapper
def decorator2(func):
def wrapper():
print("Decorator 2")
func()
return wrapper
@decorator1
@decorator2
def say_hello():
print("Hello!")
在这个例子中,当我们调用 say_hello() 函数时,首先是 decorator2(say_hello) 返回的新函数 wrapper() 被调用,然后是 decorator1(say_hello) 返回的新函数 wrapper() 被调用。
5. 内置装饰器
Python 提供了一些内置的装饰器,如 @staticmethod、@classmethod 和 @property,它们分别用于创建静态方法、类方法和属性。
class MyClass:
@staticmethod
def my_static_method():
print("This is a static method.")
@classmethod
def my_class_method(cls):
print("This is a class method.")
@property
def my_property(self):
print("This is a property.")
在这个例子中,my_static_method() 是一个静态方法,my_class_method() 是一个类方法,my_property 是一个属性。
文章名称:python3装饰器详解_装饰
转载来于:http://www.jxjierui.cn/article/cddedhp.html


咨询
建站咨询
