作业
1.建立一个汽车类Auto,包括轮胎个数,汽车颜色,车身重量,速度等属性,
并通过不同的构造方法创建实例。至少要求 汽车能够加速 减速 停车。
再定义一个小汽车类CarAuto 继承Auto 并添加空调、CD属性,
并且重新实现方法覆盖加速、减速的方法
import time
import sys
import math
import random
class Auto:
def __init__(self, weight, color, speed, num_tyre=4):
self.weight = weight
self.color = color
self.speed = speed
self.num_tyre = num_tyre
def accelerate_slow_down(self, throttle):
if throttle == 1:
print("油门被踩下")
count = 1
while True:
self.speed = self.speed + self.speed*(count**2)/500
count += 1
time.sleep(1)
print(self.speed)
if self.speed >= 180:
print("车速太快,请刹车")
break
elif throttle == 0:
print("油门松开")
count = 1
while True:
self.speed = self.speed - self.speed * (count ** 2) / 200
count += 1
time.sleep(1)
print(self.speed)
if self.speed <= 20:
print("车速太慢了可以加点油了")
break
elif throttle == 2:
print("请减速停车")
print("踩刹车")
count = 1
while True:
self.speed = self.speed - self.speed * (count ** 2) / 100
count += 1
time.sleep(1)
print(self.speed)
if self.speed <= 0:
print("车已经停好了")
break
else:
print("匀速行驶")
p1 = Auto("3T", 'white', 60)
p1.accelerate_slow_down(2)
class CarAuto(Auto):
def __init__(self, air, cd):
super().__init__("3T", 'white', 80)
self.air = air
self.cd = cd
def accelerate_slow_down(self, throttle):
if throttle == 1:
print("油门被踩下")
count = 1
while True:
self.speed = self.speed + self.speed*(count**2)/400
count += 1
time.sleep(1)
print(self.speed)
if self.speed >= 180:
print("车速太快,请刹车")
break
elif throttle == 0:
print("油门松开")
count = 1
while True:
self.speed = self.speed - self.speed * (count ** 2) / 240
count += 1
time.sleep(1)
print(self.speed)
if self.speed <= 20:
print("车速太慢了可以加点油了")
break
elif throttle == 2:
print("请减速停车")
print("踩刹车")
count = 1
while True:
self.speed = self.speed - self.speed * (count ** 2) / 120
count += 1
time.sleep(1)
print(self.speed)
if self.speed <= 0:
print("车已经停好了")
else:
print("匀速行驶")
p2 = CarAuto(0, 1)
p2.accelerate_slow_down(1)
2.创建一个Person类,添加一个类字段用来统计Perosn类的对象的个数
print()
class Count:
count = 0
class Person(Count):
def __init__(self):
Count.count += 1
def student(self):
Count.count += 1
p1 = Person()
p1.student()
print(p1.count) # 2
3.创建一个动物类,拥有属性:性别、年龄、颜色、类型 ,
要求打印这个类的对象的时候以'/XXX的对象: 性别-? 年龄-? 颜色-? 类型-?/' 的形式来打印
print()
class Animal:
def __init__(self, sex, age, color, type_a):
self._sex = sex
self.age = age
self.color = color
self.type_a = type_a
@property
def sex(self):
if self._sex == 1:
return '公'
elif self._sex == 0:
return '母'
else:
return '输入错误'
def print_type(self, name):
print("%s的对象: 性别-%s,年龄-%s,颜色-%s,类型-%s"
% (name, self.sex, self.age, self.color, self.type_a))
#
# @property
# def sex(self):
# if self._sex == 1:
# return '公'
# elif self._sex == 0:
# return '母'
# else:
# return '输入错误'
p1 = Animal(0, 18, 'yellow', 'bird')
# print(p1)
p1.print_type('燕子') # 燕子的对象: 性别-母,年龄-18,颜色-yellow,类型-bird
4.写一个圆类, 拥有属性半径、面积和周长;
要求获取面积和周长的时候的时候可以根据半径的值把对应的值取到。
但是给面积和周长赋值的时候,程序直接崩溃,并且提示改属性不能赋值
print()
class Circle:
def __init__(self, radius):
if isinstance(radius, int) or isinstance(radius, float):
self._radius = radius
else:
raise ValueError
self._area = math.pi * (radius**2)
self._perimeter = math.pi * (radius*2)
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
if not (isinstance(value, int) or isinstance(value, float)):
raise ValueError
self._radius = value
@property
def area(self):
self._area = math.pi * (self._radius ** 2)
return self._area
@area.setter
def area(self, value):
print("该属性不能修改")
raise ValueError
@property
def perimeter(self):
self._perimeter = math.pi * (self._radius * 2)
return self._perimeter
@perimeter.setter
def perimeter(self, value):
print("该属性不能修改")
raise ValueError
p1 = Circle(5)
# print(p1.area)
p1.radius = 4
print(p1.area)
print()
5.写一个扑克类, 要求拥有发牌和洗牌的功能(具体的属性和其他功能自己根据实际情况发挥)
print()
class Pock:
number = 54
nums = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
type_p = ['♥️', '♠️', '♣️', '♦️']
pocker = []
def __init__(self, kind, back_color):
self.kind = kind
self.back_color = back_color
# 创建一副牌
@staticmethod
def establish():
for type_i in Pock.type_p:
for num in Pock.nums:
Pock.pocker.append('%s%s' % (type_i, num))
Pock.pocker.extend(["大王", "小王"])
return Pock.pocker
# 洗牌
def cut_brand(self):
random.shuffle(Pock.pocker)
return Pock.pocker
# 发牌
def deal(self):
poker_iter = iter(Pock.pocker)
num = 1
p_1 = []
p_2 = []
p_3 = []
for _ in range(17*3):
if num == 1:
p_1.append(next(poker_iter))
elif num == 2:
p_2.append(next(poker_iter))
elif num == 3:
p_3.append(next(poker_iter))
num = 0
num += 1
return p_1, p_2, p_3, list(poker_iter)
if __name__ == '__main__':
p1 = Pock('1', 'yellow')
print(p1.establish()) # 54
print(p1.cut_brand())
print(p1.deal())
from enum import Enum,unique
from random import shuffle
# 1.写一个扑克类, 要求拥有发牌和洗牌的功能(具体的属性和其他功能自己根据实际情况发挥)
@unique
class PokerNum(Enum):
J = 11, 'J', 11
Q = 12, 'Q', 12
K = 13, 'K', 13
A = 1, 'A', 14
TWO = 2, '2', 15
BigJoker = 15, '大王', 17
SmallJoker = 14, '小王', 16
@unique
class PokerColor(Enum):
Club = '♣'
Diamond = '♦'
Heart = '♥'
Spade = '♠'
Space = ''
class Poker:
def __init__(self, num: PokerNum, color: PokerColor):
self.num = num
self.color = color
def __repr__(self):
if isinstance(self.num, PokerNum):
return str(self.color.value) + str(self.num.value[1])
return str(self.color.value)+str(self.num)
def __gt__(self, other):
if isinstance(self.num, PokerNum):
a = self.num.value[2]
else:
a = self.num
if isinstance(other.num, PokerNum):
b = other.num.value[2]
else:
b = other.num
return a > b
class Game:
# 斗地主
def __init__(self):
pokers = []
colors = [PokerColor.Club, PokerColor.Diamond, PokerColor.Heart, PokerColor.Spade]
nums = [PokerNum.A, PokerNum.TWO, 3, 4, 5, 6, 7, 8, 9, 10, PokerNum.J, PokerNum.Q, PokerNum.K]
for num in nums:
for color in colors:
p = Poker(num, color)
pokers.append(p)
pokers.extend([Poker(PokerNum.SmallJoker, PokerColor.Space), Poker(PokerNum.BigJoker, PokerColor.Space)])
self.pokers = pokers
self.pokers_iter = iter(self.pokers)
# 洗牌
def shuffling(self):
shuffle(self.pokers)
self.pokers_iter = iter(self.pokers)
# 斗地主发牌方式
def deal1(self):
ps1 = []
ps2 = []
ps3 = []
for _ in range(17):
ps1.append(next(self.pokers_iter))
ps2.append(next(self.pokers_iter))
ps3.append(next(self.pokers_iter))
ps1.sort(reverse=True)
ps2.sort(reverse=True)
ps3.sort(reverse=True)
return ps1, ps2, ps3, list(self.pokers_iter)
game1 = Game()
game1.shuffling()
p1, p2, p3, di = game1.deal1()
print(p1)
print(p2)
print(p3)
print('底牌:', di)
print()
6.(尝试)写一个类,其功能是:
1.解析指定的歌词文件的内容
2.按时间显示歌词 提示:歌词文件的内容一般是按下面的格式进行存储的。
歌词前面对应的是时间,在对应的时间点可以显示对应的歌词
[00:00.20]蓝莲花
[00:00.80]没有什么能够阻挡
[00:06.53]你对自由地向往
[00:11.59]天马行空的生涯
[00:16.53]你的心了无牵挂
[02:11.27][01:50.22][00:21.95]穿过幽暗地岁月
[02:16.51][01:55.46][00:26.83]也曾感到彷徨
[02:21.81][02:00.60][00:32.30]当你低头地瞬间
[02:26.79][02:05.72][00:37.16]才发觉脚下的路
[02:32.17][00:42.69]心中那自由地世界
[02:37.20][00:47.58]如此的清澈高远
[02:42.32][00:52.72]盛开着永不凋零
[02:47.83][00:57.47]蓝莲花
class Lyric:
def __init__(self, time, word):
value = float(time[1:3])*60 + float(time[4:])
self.time = value
self.word = word
def __repr__(self):
return '<'+str(self.time) + ':' + self.word+'>'
def __gt__(self, other):
return self.time > other.time
class LyricAnalysis:
def __init__(self, name):
# 歌名
self.name = name
self.__all_lyrics = []
def get_word(self, time):
# =======解析歌词文件======
if not self.__all_lyrics:
print('解析歌词')
with open('files/'+self.name) as f:
while True:
line = f.readline()
if not line:
break
lines = line.split(']')
word = lines[-1]
for t in lines[:-1]:
lyric = Lyric(t, word)
self.__all_lyrics.append(lyric)
# 排序
self.__all_lyrics.sort(reverse=True)
# ==========获取歌词==========
for lyric in self.__all_lyrics:
if lyric.time <= time:
return lyric.word
ly = LyricAnalysis('蓝莲花')
print('===:', ly.get_word(123))
print('===:', ly.get_word(10))
print('===:', ly.get_word(89))