使用装饰器实现一个计数器函数call_counter,被装饰的函数func每被调用一次计数器数值count增加1,并打印调用次数f'{func.__name__} called {count} times'.
时间: 2023-05-17 10:05:16 浏览: 112
好的,这是一个很常见的装饰器问题,以下是实现代码:
```python
def call_counter(func):
count = 0
def wrapper(*args, **kwargs):
nonlocal count
count += 1
print(f'{func.__name__} called {count} times')
return func(*args, **kwargs)
return wrapper
```
使用这个装饰器,可以将它应用到任何需要计数的函数上,例如:
```python
@call_counter
def foo():
print('Hello, world!')
foo()
foo()
```
输出结果为:
```
foo called 1 times
Hello, world!
foo called 2 times
Hello, world!
```
相关问题
一个线程 1 让线程 2 去调用一个函数用装饰器怎么实现python demo
可以使用装饰器来实现这个功能,示例代码如下:
```python
def thread_control(func):
def wrapper(*args, **kwargs):
# 线程1调用,等待线程2执行完毕
event = threading.Event()
thread2 = threading.Thread(target=func, args=args, kwargs=kwargs)
thread2.start()
event.wait()
return wrapper
@thread_control
def func_to_be_called():
# 线程2调用的函数
print('This function is being called by Thread 2.')
# 通知线程1可以继续执行
event.set()
# 线程1调用
func_to_be_called()
```
这个装饰器函数 `thread_control()` 可以用来封装任意需要在另一个线程中执行的函数。调用被装饰的函数时,被封装的函数会在新开的线程中执行,而调用者的线程则会被阻塞,直到被封装的函数执行完毕后才会继续执行。在被封装的函数中需要通知调用者线程可以继续执行时,可以调用 `event.set()` 来设置一个事件,调用者线程通过 `event.wait()` 来等待这个事件被设置。
请实现一个装饰器,通过一次调用使函数重复执行5次
好的,以下是装饰器代码,可以实现函数重复执行5次:
```
def repeat(num):
def decorator(func):
def wrapper(*args, **kwargs):
for i in range(num):
func(*args, **kwargs)
return wrapper
return decorator
@repeat(5)
def my_func():
print("Hello, World!")
my_func()
```
输出结果为:
```
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)