Source From Here
Question
Let's say I have a decorator which will be used to count the times of a function is executed:
For example:
Then I have new function say_hello
How can I dynamically add decorator on it so to count the times of execution of it?
HowTo
It is a bit complicated. Let's say your module is test.py. Then you can do it this way:
Let's say I have a decorator which will be used to count the times of a function is executed:
- def counted(f):
- def wrapped(*args, **kwargs):
- wrapped.calls += 1
- return f(*args, **kwargs)
- wrapped.calls = 0
- return wrapped
- @counted
- def say_hi(name):
- print(f"Hi, {name}")
Then I have new function say_hello
- def say_hello(name):
- print(f"Hello, {name}")
HowTo
It is a bit complicated. Let's say your module is test.py. Then you can do it this way:
沒有留言:
張貼留言