举一个python装饰器的列子
时间: 2024-02-08 09:40:08 浏览: 29
当然可以,Python装饰器是一种高级语法,常用于增强函数的功能或修改函数的行为。例如,下面这个装饰器可以在函数执行前后打印出函数名和参数:
```
def log(func):
def wrapper(*args, **kwargs):
print(f"Calling function {func.__name__} with args {args} and kwargs {kwargs}")
result = func(*args, **kwargs)
print(f"Function {func.__name__} returned {result}")
return result
return wrapper
@log
def add(x, y):
return x + y
add(2, 3)
```
运行上述代码,输出结果如下:
```
Calling function add with args (2, 3) and kwargs {}
Function add returned 5
```
可以看到,装饰器成功地在函数执行前后打印了相关信息,增强了函数的功能。
相关问题
写一个python装饰器的例子
这是一个简单的python装饰器示例:def my_decorator(func):
def wrapper(*args, **kwargs):
print("Before calling " + func.__name__)
func(*args, **kwargs)
print("After calling " + func.__name__)
return wrapper@my_decorator
def say_hello(name):
print("Hello, " + name)say_hello("John")输出:
Before calling say_hello
Hello, John
After calling say_hello
解释一下python的装饰器,举个例子
Python的装饰器是一种能够在不修改源代码的情况下,对函数或类进行扩展或修改的语法。它是一种函数或类,接收另一个函数或类作为参数,然后执行一些操作,最后返回修改后的函数或类。
举个例子,假设我们有一个函数需要记录其执行时间:
```python
import time
def func():
start_time = time.time()
# do something...
end_time = time.time()
print(f"Function took {end_time - start_time} seconds to execute.")
```
但是这个实现方式非常繁琐,我们可以使用装饰器来简化它:
```python
import time
def timer_decorator(func):
def wrapper():
start_time = time.time()
func()
end_time = time.time()
print(f"Function took {end_time - start_time} seconds to execute.")
return wrapper
@timer_decorator
def func():
# do something...
func()
```
我们定义了一个名为`timer_decorator`的装饰器函数,它接收一个函数`func`作为参数,并返回一个新的函数`wrapper`,在`wrapper`中我们记录了函数执行前后的时间并输出时间差。最后,我们使用`@timer_decorator`将`func`函数改造成了一个新的函数,该新函数已经被添加了计时功能。