1. 建立一个汽车类Auto,包括轮胎个数,汽车颜色,车身重量,速度等属性,并通过不同的构造方法创建实例。至少要求 汽车能够加速 减速 停车。 再定义一个小汽车类CarAuto 继承Auto 并添加空调、CD属性,并且重新实现方法覆盖加速、减速的方法
class Auto:
def __init__(self, tyre=4, color='白色', weight=2, speed=0):
self.tyre = tyre
self.color = color
self.weight = weight
self.seppd = speed
def add_speed(self):
self.seppd += 2
if self.seppd >= 180:
self.seppd = 180
def sub_seppd(self):
self.seppd -= 2
if self.seppd == 0:
self.seppd = 0
def stop(self):
self.seppd = 0
class AirConditioner:
def __init__(self, breed='空调', power=1, type='冷暖'):
self.breed = breed
self.power = power
self.type = type
class CD:
def __init__(self, breed='索尼', color='黑色', price=10000):
self.breed = breed
self.color = color
self.price = price
class CarAuto(Auto):
def __init__(self, tyre=4, color='白色', weight=2, speed=0):
super(CarAuto, self).__init__(tyre, color, weight, speed)
self.air_conditioner = AirConditioner()
self.CD = CD()
def add_speed(self):
self.seppd += 4
if self.seppd >= 240:
self.seppd = 240
def sub_seppd(self):
self.seppd -= 4
if self.seppd == 0:
self.seppd = 0
2. 创建一个Person类,添加一个类字段用来统计Perosn类的对象的个数
class Person:
count = 0
def __init__(self):
if self.__class__ == Person: # 判断类型
Person.count += 1
class Student(Person):
pass
stu = Student()
print(Person.count)
cls = Person()
print(Person.count)
3. 创建一个动物类,拥有属性:性别、年龄、颜色、类型 ,
要求打印这个类的对象的时候以'/XXX的对象: 性别-? 年龄-? 颜色-? 类型-?/' 的形式来打印
class Animals:
def __init__(self, type='陆上跑的', color='黑色', age=0, gender='母'):
self.type = type
self.color = color
self.age = age
self.gender = gender
def __repr__(self):
# self.__class__.__name_ 打印对象
return '/{}的对象: 性别-{} 年龄-{} 颜色-{} 类型-{}/'.format(self.__class__.__name__, self.gender, self.age, self.color, self.type)
a1 = Animals()
print(a1)
4. 写一个圆类, 拥有属性半径、面积和周长;要求获取面积和周长的时候的时候可以根据半径的值把对应的值取到。但是给面积和周长赋值的时候,程序直接崩溃,并且提示改属性不能赋值
class ReadOnlyError(Exception):
def __str__(self):
return '该属性不能赋值'
class Circle:
pi = 3.1415926
def __init__(self, radius):
self.radius = radius
self._area = 0
self._perimeter = 0
@property
def area(self):
return Circle.pi * self.radius * self.radius
@area.setter
def area(self, value):
raise ReadOnlyError
@property
def perimeter(self):
return 2 * Circle.pi * self.radius
@perimeter.setter
def perimeter(self, value):
raise ReadOnlyError
c1 = Circle(10)
print(c1.area, c1.perimeter)
# c1.area = 100
5. 写一个扑克类, 要求拥有发牌和洗牌的功能(具体的属性和其他功能自己根据实际情况发挥)
# 导入枚举模块
import enum
from random import shuffle
class PokerNum(enum.Enum):
"""
创建枚举类
"""
J = (11, 'J')
Q = (12, 'Q')
K = (13, 'K')
A = (14, 'A')
Two = (15, '2')
Three = (3, '3')
Four = (4, '4')
Five = (5, '5')
Six = (6, '6')
Seven = (7, '7')
Eight = (8, '8')
Nine = (9, '9')
Ten = (10, '10')
Joker_S = (16, 'joker')
Joker_D = (17, 'JOKER')
# print(PokerNum.J, PokerNum.K.value)
# print(PokerNum.__members__)
# for item in PokerNum.__members__.items():
# print(item, type(item[1]))
class Poker:
"""
扑克类
创建对象:颜色和张数
"""
def __init__(self, color, num):
self.color = color # ♥ ♠ ♣ ♦
self.num = num # 2-10,J,Q,K,A;小王,大王
def __repr__(self):
return '{}{}'.format(self.color, self.num.value[1])
# 让Poker对象可以比较大小(>):重载魔法方法
def __gt__(self, other):
return self.num.value[0] > other.num.value[0]
class PockerGame:
"""
玩游戏类
"""
def __init__(self):
self.pokers = []
# 创建牌
nums = PokerNum.__members__.items()
colors = ['♥', '♠', '♣', '♦']
for num in nums:
if num[1] == PokerNum.Joker_S or num[1] == PokerNum.Joker_D:
continue
for color in colors:
# if num[1] != PokerNum.Joker_S and num[1] != PokerNum.Joker_D:
# 创建牌对象
p = Poker(color, num[1])
self.pokers.append(p)
self.pokers.append(Poker('', PokerNum.Joker_S))
self.pokers.append(Poker('', PokerNum.Joker_D))
print(self.pokers)
def __shuffle(self):
"""
定义为私有的方法
洗牌
方法1:转换为集合
方法2:random.shuffle(列表)
:return:
"""
# print(set(self.pokers))
shuffle(self.pokers)
print(self.pokers)
def deal(self):
"""
在发牌之前先调用洗牌
:return:
"""
self.__shuffle()
poker_iter = iter(self.pokers)
p1 = []
p2 = []
p3 = []
for _ in range(17):
p1.append(next(poker_iter))
p2.append(next(poker_iter))
p3.append(next(poker_iter))
# 排序
# p1.sort(key=lambda item: item.num.value[0], reverse=True)
# p2.sort(key=lambda item: item.num.value[0], reverse=True)
# p3.sort(key=lambda item: item.num.value[0], reverse=True)
p1.sort(reverse=True)
p2.sort(reverse=True)
p3.sort(reverse=True)
return p1,p2,p3,list(poker_iter)
game = PockerGame()
# game.shuffle()
print(game.deal())
# p1 = Poker('♠', PokerNum.J)
# p2 = Poker('♦', PokerNum.K)
# print(p1<p2)
6. (尝试)写一个类,其功能是:1.解析指定的歌词文件的内容 2.按时间显示歌词 提示:歌词文件的内容一般是按下面的格式进行存储的。歌词前面对应的是时间,在对应的时间点可以显示对应的歌词
class Lyric:
def __init__(self):
self._time = 0 # 时间
self.word = '' # 歌词
@property
def time(self):
return self._time
@time.setter # 把时间转为秒的形式
def time(self, value):
fen = float(value[1:3])
miao = float(value[4:])
self._time = fen*60 + miao
def __repr__(self):
"""自定义打印"""
return '{}:{}'.format(self.time, self.word)
def __lt__(self, other):
return self._time > other._time
class LyricAnalysis:
def __init__(self, song_name: str):
self.__song_name = song_name # 歌名(对象属性)
self.__lyrics = [] # 用于存储歌词与时间
def __analysis_file(self):
# 读歌词文件中的内容
with open('file/'+self.__song_name + '.lrc', 'r', encoding='utf-8') as r_f:
while True:
line_content = r_f.readline()
if not line_content:
break
# 将时间和歌词分离
lines = line_content.split(']')
# 时间点和歌词产生一一对应关系
# print(lines)
# word = lines[-1][:-1] # 让歌词一行显示
word = lines[-1]
for time in lines[:-1]:
lyric = Lyric()
lyric.time = time
lyric.word = word
self.__lyrics.append(lyric)
# 对歌词进行排序(先重写比较大小的方法)
self.__lyrics.sort()
# print(self.__lyrics)
def get_lyric(self, time):
"""根据时间获取歌词"""
if not self.__lyrics: # 在实现功能之前先解析歌词文件(判断是否已经解析过)
self.__analysis_file()
# 找到第一个小于指定时间的歌词对象
for lyric in self.__lyrics:
if lyric.time <= time:
return lyric.word
l1 = LyricAnalysis('蓝莲花')
print(l1.get_lyric(10))