-
写一个装饰器@tag要求满足如下功能:
def tag(name): def new_func1(func): def new_func2(*args, **kwargs): result = func(*args, **kwargs) return f'<{name}>{result}</{name}>' return new_func2 return new_func1 @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>
-
为函数写一个装饰器,根据参数不同做不同操作。
def tag2(flag): def new_func1(func): def new_func2(*args, **kwargs): result = func(*args, **kwargs) if type(result) in (int, float, bool, complex): if flag: result += 100 return result elif not flag: result -= 100 return result else: return result return new_func2 return new_func1 @tag2(True) def func1(x, y): return x + y @tag2(False) def func2(x, y): return x * y print(func1(100, 200)) # 400 print(func2(10, 20)) # 100
-
为函数写一个装饰器,根据不同的运算符和数据对原函数的返回值进行相应的数值操作
def tag3(operator, date): def new_func1(func): def new_func2(*args, **kwargs): result = func(*args, **kwargs) if operator == '+' and date == 100: result += 100 return result if operator == '-' and date == 20: result -= 20 return result if operator == '*' and date == 3: result *= 3 return result if operator == '/' and date == 2: result /= 2 return result else: return result return new_func2 return new_func1 @tag3('+', 100) def func3(n): return n+1 print(func3(5)) # 106
-
写一个斗地主发牌器
import random cards = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'] colors = ['♥', '♠', '♦', '♣'] all_cards = ['大王', '小王'] for x in colors: for y in cards: all_cards.append(x + y) random.shuffle(all_cards) print('洗好牌后的排序:', all_cards) dealer = (i for i in all_cards) # 生成式 def fapai(): palyer_a = [] palyer_b = [] palyer_c = [] m = 1 while m < 18: palyer_a.append(next(dealer)) print('玩家A的牌:', palyer_a) palyer_b.append(next(dealer)) print('玩家B的牌:', palyer_b) palyer_c.append(next(dealer)) print('玩家C的牌:', palyer_c) m += 1 print('地主要翻的牌:', next(dealer), next(dealer), next(dealer)) fapai()
day12 作业
最新推荐文章于 2024-08-31 21:39:38 发布