-
为函数写一个装饰器,在函数执行之后输出 after
def after_decorator(fn): def new_fn(*args,**kwargs): result = fn(*args,**kwargs) print('after') return result return new_fn @after_decorator def sum(x,y): result = x + y print(result) sum(2,3)
-
为函数写一个装饰器,把函数的返回值 乘2再返回值
def double(fn): def new_fn(*args,**kwargs): result = fn(*args,**kwargs) if type(result) in (float,int): result = result*2 return result return new_fn @double def sum(x,y): sum1 = x + y return sum1 print(sum(2,3))
-
写一个装饰器@tag要求满足如下功能:
@tag
def render(text):
# 执行其他操作
return text
@tag
def render2():
return 'abc'
print(render('Hello')) # 打印出: <p>Hello</p>
print(render2()) # 打印出: <p>abc</p>
def tag(fn):
def new_fn(*args,**kwargs):
result = fn(*args,**kwargs)
result = f'<p>{result}</p>'
return result
return new_fn
-
写一个创建一副扑克牌的生成器。
def poker(flower_color ='黑桃'): for x in ('A',2,3,4,5,6,7,8,9,10,'J','Q','K'): yield f'{flower_color}{x}' result = poker(flower_color ='黑桃') print(next(result))
-
使用递归函数画出以下图形:
n = 5 ***** **** *** ** * n = 4 **** *** ** * def star(n): if n > 1: print('*'*n) star(n - 1) print('*') star(4)