defadd_num(flag):defadd(f):defnew_f(*args,**kwargs):
re=f(*args,**kwargs)if flag ==True:return re+100if flag ==False:return re-100# return re+100 if flag==True else re-100 # 三目return new_f
return add
@add_num(flag=True)deffunc1(x,y):return x+y
@add_num(flag=False)deffunc2(a,b):return a*b
print(func1(10,20))print(func2(6,5))
# 3.为函数写一个装饰器,根据不同的运算符和数据对原函数的返回值进行相应的数值操作
defcreate_caozuo(fuhao,num):defcaozuo(f):defnew_f(*args,**kwargs):
re=f(*args,**kwargs)iftype(re)in(int,float,complex,bool):if fuhao =='+':return re+num
if fuhao =='-':return re-num
if fuhao =='*':return re*num
if fuhao =='/':return re/num
else:return re
else:return re
return new_f
return caozuo
@create_caozuo(fuhao='*',num=100)deffunc4(x):return x
print(func4(6))
#4.写一个斗地主发牌器
#斗地主发牌import random
#生成牌库,不考虑花色defget_library():
Library=[x for x in('A','2','3','4','5','6','7','8','9','10','J','K','Q')for y inrange(4)]
Library.append('big_King')#牌库加入大王
Library.append('small_King')#牌库加入小王return Library #返回牌库#定义:先从牌库抽出三张地主牌的方法defget_dizhu_pai():
dizhu_list =[]for i inrange(3):
d=random.choice(library)#从指定序列中随机抽取一个元素
dizhu_list.append(d)
library.remove(d)return dizhu_list
# 定义:给玩家发牌的方法deffapai(now_library:list):
player=[]# 定义该玩家的牌的列表for i inrange(17):# 获得地主牌前,每个玩家有17张牌
pai=random.choice(now_library)# 从牌库随机去一张牌
player.append(pai)# 将牌发给玩家
now_library.remove(pai)# 将发出去的牌从牌库删除return player # 返回玩家的牌列表#调用方法生成牌库,library就是牌库
library=get_library()print(f'牌库:{library}')#调用方法,从牌库中抽取三张地主牌
dizhu_list=get_dizhu_pai()print(f'地主牌:{dizhu_list}')#调用方法给每位玩家发牌
player1=fapai(library)
player2=fapai(library)
player3=fapai(library)# 三个玩家摇点 谁的点数大,地主牌给谁
get_score=Truewhile get_score:
p1_score=random.randint(1,100)
p2_score=random.randint(1,100)
p3_score=random.randint(1,100)if p1_score != p2_score !=p3_score :
get_score =Falseifmax(p1_score,p2_score,p3_score)==p1_score:print('玩家1是地主')
player1+=dizhu_list
elifmax(p1_score,p2_score,p3_score)==p2_score:print('玩家2是地主')
player2 += dizhu_list
else:print('玩家3是地主')
player3 += dizhu_list
print(f'玩家1:{player1}')print(f'玩家2:{player2}')print(f'玩家3:{player3}')print('发牌结束,请开始游戏')