Exercises of Python Decorator
- 2021-12-13 08:53:18
- OfStack
Directory 1. Please implement a decorator, the return value of the function +100 and then return 2. Please implement a decorator, through a call to make the function repeated 5 times 3. Please implement a decorator every time the function is called, the name of the function and the time point of calling the function are written into the file
1. Please implement a decorator, and return the value of the function +100 and then return
def wapper(func):
def innner(*args,**kwargs):
ret=func(*args,**kwargs)
ret=print(ret+100)
return ret
return innner
@wapper
def func(number):
return int(number)
func(100)
### Results: 200
2. Please implement a decorator and repeat the function 5 times through 1 call
#Python Learning and communication group: 725638078
def wapper(func):
def innner(*args,**kwargs):
count=0
while count<5:
func(*args,**kwargs)
count+=1
return innner
@wapper
def func():
print(" Execute ")
func()
3. Please implement a decorator. When calling a function, write the name of the function and the time point of calling the function into the file
import time
def wapper(func):
def inner(*args,**kwargs):
with open("log",encoding="utf-8",mode="a+") as f:
structime=time.localtime()
f.write(f' Beijing Time: {time.strftime("%Y-%m-%d %H:%M:%S",structime)} The name of the function is: {func.__name__}\n')
ret=func(*args,**kwargs)
return ret
return inner
@wapper
def func():
print(" Execute ")
func()
At the end, I recommend a very good learning tutorial for you, hoping to help you learn Python!