一、函数参数注释
相当于文档,与之前没有区别
你写好了一个函数,然后想为这个函数的参数增加一些额外的信息(每个参数的类型),这样的话其他调用者就能清楚的知道这个函数应该怎么使用。
示例:
def add(x:int, y:int) -> int:
return x + y
python解释器不会对这些注解添加任何的语义。它们不会被类型检查,运行时跟没有加注解之前的效果也没有任何差距。
函数注解只存储在函数的 annotations 属性中。
>>> add.__annotations__
{'y': <class 'int'>, 'return': <class 'int'>, 'x': <class 'int'>}
>>>
二、练习:扑克牌模拟
任务目的
0.培养编程思维,提高分析问题能力 1.掌握类的抽象与设计 2.掌握循环,分支条件的用法 3.掌握各种集合类的使用
任务描述
1.定义一个单张扑克类(考虑需要哪些属性),定义一个一副扑克牌类,该类包含一个单张扑克对象的数组(不考虑大小王)。实现一个模拟扑克发牌洗牌的算法; 2.电脑随机发出5张牌,判断是以下哪种牌型?(提示,利用各种集合的特性可以简化判断)
Card.py
class Card:
def __init__(self,color,value):
self.value = value
self.color = color
def __repr__(self):
strvalue = str(self.value)
if self.value == 11:
strvalue = 'J'
if self.value == 12:
strvalue = 'Q'
if self.value == 13:
strvalue = 'K'
if self.value == 1:
strvalue = 'A'
return self.color + strvalue
if __name__ == '__main__':
cardA = Card('红桃',1)
print(cardA)
Poke.py
from Card import Card
import random
color_tuple = ('红桃','方片','草花','黑桃')
class Poke:
def __init__(self):
self.cards = []
for color in color_tuple:
for value in range(1,14):
card = Card(color,value)
self.cards.append(card)
def output(self):
index = 1
for card in self.cards:
print(card,end='\t')
if index % 13 == 0:
print()
index+=1
if __name__ == '__main__':
poke = Poke()
poke.output()
random.shuffle(poke.cards)
print('-'*70)
poke.output()
hands = poke.cards[:5]
# hands[0] = poke.cards[13]
print(hands)
colorsLst = [card.color for card in hands]
print(colorsLst)
colorset = set(colorsLst)
print(colorset)
valueLst = [card.value for card in hands]
print(valueLst)
valueset = set(valueLst)
print(valueset)
valueLstSorted = sorted(valueLst)
print(valueLstSorted)
bIsSameColor = False
bIsShunzi = False
if len(valueset) == 5 and valueLstSorted[-1] - valueLstSorted[0] == 4:
bIsShunzi = True
if len(colorset) == 1:
bIsSameColor = True
if bIsSameColor == True and bIsShunzi == True:
print('同花顺')
elif bIsShunzi:
print('顺子')
elif bIsSameColor:
print('同花')
elif len(valueset) == 4:
print('一对')
elif len(valueset) == 5:
print('杂牌')
#4带1或者3带2
elif len(valueset) == 2:
if valueLst.count(valueLst[0]) == 1 or valueLst.count(valueLst[0]) == 4:
print('4带1')
else:
print('3带2')
#311或221
else:
isThreeOneOne = False
for value in valueLst:
if valueLst.count(value) == 3:
isThreeOneOne = True
break
if isThreeOneOne == True:
print('311')
else:
print('221')
注意:
__repr__更底层,有__str__的全部功能,比__str__更强大,当对象在字典或集合中被打印时仍然可以进入__repr__.
三、练习:python类和对象---分数类型定义
定义一个分数类
实现分数的加减乘除运算,约分运算,和比较大小
一般用gcd表示最大公约数
注意:
一个思想:测试驱动开发,写了一些代码,就测试一下
def gcd(m, n):
while m % n != 0:
oldm = m
oldn = n
n = m % n
m = oldn
return n
class Fraciton:
def __init__(self,top,bottom):
if isinstance(top,int) == True:
self.num = top
else:
raise ValueError('top must to be int')
if isinstance(bottom,int) == True:
self.den = bottom
else:
raise ValueError('bottom must to be int')
common = gcd(self.num,self.den)
self.num = self.num // common
self.den = self.den // common
def __str__(self):
return str(self.num) + ' / ' + str(self.den)
def __repr__(self):
return str(self.num) + ' / ' + str(self.den)
def __add__(self,other):
# print('__add__')
newnum = self.num*other.den+self.den*other.num
newden = self.den*other.den
fracResult = Fraciton(newnum,newden)
return fracResult
def __sub__(self, other):
pass
def __mul__(self, other):
pass
def __truediv__(self, other):
pass
def __eq__(self,other):
return self.num*other.den == self.den*other.num
def __ne__(self, other):
print('__ne__')
return self.num*other.den != self.den*other.num
#great equal
def __ge__(self, other):
pass
#less
def __le__(self, other):
pass
#<
def __lt__(self, other):
pass
def getNum(self):
return self.num
def getDen(self):
return self.den
if __name__ == '__main__':
frac1 = Fraciton(1,3)
print(frac1)
frac2 = Fraciton(2,6)
print(frac2)
# frac1+=frac2
# result = frac1.__add__(frac2)
print(frac1)
print(frac1==frac2)
if frac2 == frac1:
print('相等')
四、练习:python自定义日期类型
设计一个日期类,能够实现与日期有关的有关操作,如计算两个日期之间的间隔,指定日期之后若干天所对应的日期,比较两个日期的大小等。
拓展功能:
- 判断该日期是一年中的第几天。
- 按照YMD(year-month-day)、MDY、DMY和default格式打印日期。
- 计算两个日期的间隔。
- 给出指定日期后多少天是那一天。
- 初始化类的时候检查是否合法。
说明文档(设计思路):
- 类设计私有变量normal_year和leap_year,在初始化类的时候将检查日期是否合法。如果不合法将返回错误。
- 比较两个日期大小时即compare函数,我摒弃了传统的日期比较方法,直接将日期转化为int类型,比较两个数字大小。
- 计算日期间隔(cal_interval)和增加天数(add_days)函数采用传统的日期操作方法。
- 在检查类是否正确时对闰年和非法变量等情况均综合考虑。
- 按照YMD(year-month-day)、MDY、DMY和default格式打印日期。
class MyDate:
def __init__(self,year,month,day):
self.__normal_year = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
self.__leap_year = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
self.not_leap = 1
if self.check(year,month,day) == True:
self.__year = year
self.__month = month
self.__day = day
else:
raise ValueError('不是一个有效的日期')
def check(self,year,month,day):
if year < 0:
return False
if month > 12 or month < 1:
return False
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
self.not_leap = 0
if day < 1 or day > self.__leap_year[month-1]:
return False
else:
if day < 1 or day > self.__normal_year[month - 1]:
return False
return True
def printf(self):
print(f'日期:{self.__year}-{self.__month}-{self.__day}')
@property
def year(self):
return self.__year
@year.setter
def year(self,year):
self.__year = year
@property
def month(self):
return self.__month
@month.setter
def month(self, month):
self.__month = month
@property
def day(self):
return self.__day
@day.setter
def day(self, day):
self.__day = day
# 0 ---> 相等 -1 ---》小于 1 ----》大于
def compare(self,other):
if self.__year > other.year:
return 1
elif self.__year == other.year:
if self.__month > other.month:
return 1
elif self.__month == other.month:
if self.__day == other.day:
return 0
elif self.__day > other.day:
return 1
else:
return -1
else:
return -1
else:
return -1
def add_days(self, day_plus):
templst = []
if self.not_leap == 0:
templst = self.__leap_year
else:
templst = self.__normal_year
#加的天数没有超过本月总天数
if templst[self.month - 1] >= self.__day + day_plus:
self.__day += day_plus
# 加的天数超过了本月总天数,但是没有超过本年剩余天数
else:
#本年还剩的天数
total = 0
for i in range(self.__month,12):
total += templst[i]
day_plus -= (templst[self.__month-1] - self.__day)
#年不用动
if total >= day_plus:
month_now = self.__month
while day_plus >= 0:
if day_plus > templst[month_now]:
day_plus -= templst[month_now]
month_now+=1
else:
self.__month = month_now
self.__day = templst[month_now] - day_plus
else:
pass
def get_day_in_the_year(self):
sum = 0
templst = []
if self.not_leap == 0:
templst = self.__leap_year
else:
templst = self.__normal_year
for month in range(self.__month-1):
sum += templst[month]
sum += self.__day
return sum
if __name__ == '__main__':
d1 = MyDate(1988,10,31)
d1.printf()
d2 = MyDate(1988,10,31)
d2.printf()
print(d2.compare(d1))
d = MyDate(2019,2,8)
print(d.get_day_in_the_year())
d.printf()
d.add_days(9)
d.printf()
网友评论