1.建立一个汽车类Auto,包括轮胎个数,汽车颜色,车身重量,速度等属性,并通过不同的构造方法创建实例。至少要求 汽车能够加速 减速 停车。再定义一个小汽车类CarAuto 继承Auto 并添加空调、CD属性,
并且重新实现方法覆盖加速、减速的方法
class Auto:
count = 0
def __init__(self, tyre, color, weight, speed):
self._tyre = tyre
self.color = color
self.weight = weight
self._speed = speed
@property
def tyre(self):
return self._tyre
@tyre.setter
def tyre(self, value):
if value <= 0:
raise ValueError
self._tyre = value
@property
def speed(self):
return '%s horses' % self._speed
@speed.setter
def speed(self, value):
if not (0 <= value <= 300):
raise ValueError
self._speed = value
def speed_up(self, num):
for i in range(0, num + 1, 5):
self._speed += i
if 0 <= self._speed <= 300:
print('正在加速')
else:
print('已到最大速!')
break
@classmethod
def slow_down(cls):
cls.count += 1
print('减速%d次' % cls.count)
@staticmethod
def parking(str=''):
if str == 'stop':
print('停车!')
else:
print('继续行驶')
class CarAuto(Auto):
count = 0
def __init__(self, tyre, color, weight, speed, CD=0, air_conditioning=1):
self._CD = CD
self._ac = air_conditioning
super().__init__(tyre, color, weight, speed)
@property
def CD(self):
if self._CD == 1:
return '有CD'
else:
return '无CD'
@property
def ac(self):
if self._ac == 1:
return '有空调'
else:
return '无空调'
def speed_up(self, num):
for i in range(0, num, 5):
self._speed += i
if 0 <= self._speed <= 300:
print('%s色小汽车已加速' % self.color)
else:
print('已到最大速!')
@classmethod
def slow_down(cls):
cls.count += 1
num = cls.count * 20
print('减速%d次,加速%d hoeses' % (cls.count, num))
auto = Auto(6, '白', '2t', 45)
print(auto.color)
print(auto.color)
print(auto.weight)
print(auto.speed)
auto.speed_up(30)
auto.slow_down()
auto.slow_down()
# 减速1次
# 减速2次
auto.parking('stop')
# 停车!
car = CarAuto(4, '白', '2t', 60, CD=1, air_conditioning=1)
print(car.tyre)
print(car.color)
print(car.weight)
print(car.speed)
print(car.CD)
print(car.ac)
car.speed_up(10)
car.slow_down()
car.parking(str='stop')
# 白
# 白
# 2t
# 45 horses
# 正在加速
# 正在加速
# 正在加速
# 正在加速
# 正在加速
# 正在加速
# 正在加速
# 减速1次
# 减速2次
# 停车!
# 4
# 白
# 2t
# 60 horses
# 有CD
# 有空调
# 白色小汽车已加速
# 白色小汽车已加速
# 减速1次,加速20 hoeses
# 停车!
2.创建一个Person类,添加一个类字段用来统计Perosn类的对象的个数
class Person:
count = 0
def __init__(self, name, age, gender):
self._name = name
self.age = age
self.gender = gender
Person.count += 1
@property
def name(self):
return self._name
@name.setter
def name(self, value):
self._name = value
@classmethod
def count_per(cls):
print('人数:%d' % cls.count)
Person.count_per()
p1 = Person('a', 12, '男')
p1.count_per()
# print(p1.name)
p2 = Person('b', 13, 'nv')
# print(p2.name)
p2.count_per()
# 人数:0
# 人数:1
# 人数:2
3.创建一个动物类,拥有属性:性别、年龄、颜色、类型 ,要求打印这个类的对象的时候以'/XXX的对象:性别-? 年龄-? 颜色-? 类型-?/' 的形式来打印
class Animal:
def __init__(self, gender, age, color, var):
self.gender = gender
self.age = age
self.color = color
self.var = var
def __str__(self):
return '性别-{} 年龄-{} 颜色-{} 类型-{}'.format(self.gender, self.age, self.color, self.var)
cat = Animal('母', 3, '黑', '猫')
print(cat)
# 性别-母 年龄-3 颜色-黑 类型-猫
4.写一个圆类, 拥有属性半径、面积和周长;要求获取面积和周长的时候的时候可以根据半径的值把对应的值取到。但是给面积和周长赋值的时候,程序直接崩溃,并且提示改属性不能赋值
from math import pi
class WriteError(Exception):
def __str__(self):
return '修改只读属性!'
class Circle:
def __init__(self, radius):
self._radius = radius
self._area = 0
self._perimeter = 0
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
if value <= 0:
raise ValueError
self._radius = value
@property
def area(self):
return pi * self._radius ** 2
@area.setter
def area(self, value):
raise WriteError
@property
def perimeter(self):
return pi * self._radius * 2
@perimeter.setter
def perimeter(self, value):
raise WriteError
c1 = Circle(3)
print(c1.area)
print(c1.perimeter)
# 28.274333882308138
# 18.84955592153876
写一个扑克类,要求拥有发牌和洗牌的功能(具体的属性和其他功能自己根据实际情况发挥)
import random
class Poker:
def __init__(self, kind):
self._kind = kind
@property
def kind(self):
if self._kind == 1:
return '斗地主'
elif self._kind == 2:
return '升级'
else:
return '没有该属性,等待完善!!!'
@kind.setter
def kind(self, value):
self._kind = value
def shuffle():
"""洗牌"""
pokers = []
nums = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
colors = ['♥️', '♠️', '♣️', '♦️']
for num in nums:
for color in colors:
pokers.append('%s%s' % (color, num))
pokers.extend(['小王', '大王'])
random.shuffle(pokers)
return pokers
pokers = shuffle()
def deal(self):
poker = Poker.pokers
a = self._kind
# print(poker)
# print(a)
if a == 1: # 斗地主
poker_iter = iter(poker)
p1 = []
p2 = []
p3 = []
num = 1
for _ in range(17 * 3):
if num == 1:
p1.append(next(poker_iter))
elif num == 2:
p2.append(next(poker_iter))
elif num == 3:
p3.append(next(poker_iter))
num = 0
num += 1
return p1, p2, p3, list(poker_iter)
elif a == 2: # 升级
poker_iter = iter(poker)
p1 = []
p2 = []
p3 = []
p4 = []
num = 1
for _ in range(48):
if num == 1:
p1.append(next(poker_iter))
elif num == 2:
p2.append(next(poker_iter))
elif num == 3:
p3.append(next(poker_iter))
elif num == 4:
p4.append(next(poker_iter))
num = 0
num += 1
return p1, p2, p3, p4, list(poker_iter)
pokers = Poker(1)
pokers.deal()
print(pokers.kind)
print(pokers.deal())
pokers = Poker(2)
pokers.deal()
print(pokers.kind)
print(pokers.deal())
# 斗地主
# (['♠️J', '♦️K', '♠️10', '♥️3', '♣️5', '♣️A', '♥️7', '♦️Q', '♥️2', '♣️J', '♦️6', '小王', '♥️8', '♠️3', '♦️9', '♦️4', '♥️K'],
# ['♥️A', '♦️2', '♥️J', '♠️2', '♣️2', '♥️4', '♥️5', '♦️J', '♣️Q', '♣️10', '♠️7', '♣️8', '♣️7', '♥️9', '♦️3', '♠️9', '♦️10'],
#['♠️Q', '♦️5', '♣️K', '♣️6', '♥️10', '♠️8', '大王', '♠️K', '♣️3', '♠️6', '♣️9', '♥️6', '♦️7', '♦️A', '♥️Q', '♦️8', '♠️4'],
# ['♠️5', '♠️A', '♣️4'])
# 升级
# (['♠️J', '♦️2', '♣️K', '♣️5', '♥️4', '大王', '♥️2', '♣️10', '♣️9', '♥️8', '♥️9', '♥️Q'],
# ['♥️A', '♦️5', '♥️3', '♣️2', '♠️8', '♦️Q', '♣️Q', '♠️6', '小王', '♣️7', '♦️A', '♦️4'],
# ['♠️Q', '♠️10', '♠️2', '♥️10', '♥️7', '♦️J', '♣️3', '♦️6', '♣️8', '♦️7', '♦️9', '♠️9'],
# ['♦️K', '♥️J', '♣️6', '♣️A', '♥️5', '♠️K', '♣️J', '♠️7', '♥️6', '♠️3', '♦️3', '♦️8'],
# ['♥️K', '♦️10', '♠️4', '♠️5', '♠️A', '♣️4'])
from enum import Enum, unique
from random import shuffle
@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)
(尝试)写一个类,其功能是:
1.解析指定的歌词文件的内容 2.按时间显示歌词
提示:歌词文件的内容一般是按下面的格式进行存储的。歌词前面对应的是时间,在对应的时间点可以显示对应的歌词
import json
import time
class Analysis:
def __init__(self, str1): # 输入歌词文件名,文件已下载
self.str1 = str1
def lyric(self):
# 读取歌词文件转换为字符串
with open('%s.txt' % self.str1, 'r', encoding='utf-8') as f:
list1 = []
while True:
string = f.readline()
list1.append(str(string))
if not string:
break
# 将歌词字符串以每行数据存入相应名字的json文件中
# print(list1)
with open('%s.json' % self.str1, 'w', encoding='utf-8') as f:
str_list = json.dumps(str(list1))
f.write(str_list)
# 读取出歌词转化为列表
with open('%s.json' % self.str1, 'r', encoding='utf-8') as f:
str2 = f.read()
str3 = json.loads(str2)
# print(str3)
# print(type(str3))
list2 = eval(str3)
# print(type(list2))
# print(list2)
return list2
# 播放歌词
def play(self):
ly = Analysis.lyric(self)
ms = 0
s = 0
m = 0
# 用时间匹配歌词
time1 = 0
while True:
str1 = '[{}:{}.{}]'.format(str(m).zfill(2), str(s).zfill(2), str(ms).zfill(2))
for x in ly:
str_ly = ''
if str1 in x:
for j in x:
if '一' <= j <= '龤':
str_ly += j
print(str1,str_ly) # 输出中文字符串歌词
str_ly = ''
time1 = m * 60 + s + ms * 0.01
# time2 = -(time1)
# print(time2)
# print(time1)
time3 = -(time2 - time1)
time.sleep(time3) # 按照歌词时间沉睡输出歌词
time2 = time1
if ms == 100: # 100毫秒增加1秒
s += 1
ms = 0
if s == 60: # 60秒增加1分钟
m += 1
s = 0
if m == 4: # 歌词时间不超过4分钟
break
ms += 1
a = Analysis('蓝莲花')
a.play()
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))
ly2 = LyricAnalysis('一首简单的歌')
print('!!!:', ly2.get_word(30))
print('!!!:', ly2.get_word(90))