-
为函数写一个装饰器,在函数执行之后输出 after
def pr_after(fn): def test(*args,**kwargs): re = fn(*args,**kwargs) return str(re)+'after' return test @pr_after def yj_sum(*num): sum = 0 for i in num: sum+=i return sum list1 = [1,2,3,4,5] print(yj_sum(*list1))
为函数写一个装饰器,把函数的返回值 +100 然后再返回。
@tag
def render(text):
# 执行其他操作
return text
@tag
def render2():
return 'abc'
print(render('Hello')) # 打印出: <p>Hello</p>
print(render2()) # 打印出: <p>abc</p>
def yj_100(fn):
def test(*args,**kwargs):
re = fn(*args,**kwargs)
return re+100
return test
@yj_100
def yj_sub(*num):
sub = 0
for i in num:
sub-=i
return sub
print(yj_sub(*list1))
- 写一个装饰器@tag要求满足如下功能:
def tag(fn):
def test(*args,**kwargs):
re = fn(*args,**kwargs)
return '<p>'+re+'</p>'
return test
@tag
def render(text):
return text
@tag
def render2():
return 'abc'
print(render('hello'))
print(render2())
- 写一个装饰器@tag要求满足如下功能(需要使用带参的装饰器,自己先自学正在一下):
def tag(name):
def wrapper(fn):
def inner(*args,**kwargs):
re = fn(*args,**kwargs)
return '<%s>'%(name)+re+'</%s>'%(name)
return inner
return wrapper
@tag(name='p')
def render(text):
return text
@tag(name='div')
def render2():
return 'abc'
print(render('hello'))
print(render2())
@tag(name='p')
def render(text):
# 执行其他操作
return text
@tag(name='div')
def render2():
return 'abc'
print(render('Hello')) # 打印出: <p>Hello</p>
print(render2()) # 打印出: <div>abc</div>
- 为函数写一个装饰器,根据参数不同做不同操作。
flag为True,则 让原函数执行后返回值加100,并返回。
flag为False,则 让原函数执行后返回值减100,并返回。
def get_chr(flag):
def warpper(fn):
def inner(*args,**kwargs):
re = fn(*args,**kwargs)
if flag == True:
return re+100
elif flag == False:
return re-100
else:
return re
return inner
return warpper
@get_chr(flag = True)
def yj_pchar():
return 100
@get_chr(flag = False)
def yjpchor():
return 100
print(yj_pchar(),yjpchor())