练习 : 面向对象
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.speed = speed
def add_speed(self):
self.speed += 2
if self.speed >= 180:
self.speed = 180
def sub_speed(self):
self.speed -= 2
if self.speed < 0:
self.speed = 0
def stop(self):
self.speed = 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=1000):
self.breed = breed
self.color = color
self.price = price
class CarAuto(Auto):
def __init__(self, tyre=4, color='白色', weight=2, speed=0):
super().__init__(tyre, color, weight, speed)
self.air_conditioner = AirConditioner()
self.cd = CD()
def add_speed(self):
self.speed += 4
if self.speed >= 240:
self.speed = 240
def sub_speed(self):
self.speed -= 4
if self.speed <= 0:
self.speed = 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)
p1 = Person()
p2 = Person()
print(Person.count)
### 3.创建一个动物类,拥有属性:性别、年龄、颜色、类型 (要求打印这个类的对象的时候以'/XXX的对象: 性别-? 年龄-? 颜色-? 类型-?/' 的形式来打印)
```python
class Animal:
def __init__(self, gender='雌', color='黑色', age=2, type='爬行'):
self.gender = gender
self.color = color
self.age = age
self.type = type
def __repr__(self):
return '/{}的对象: 性别-{} 年龄-{} 颜色-{} 类型-{}/'.format(self.__class__.__name__, self.gender, self.age, self.color, self.type)
a1 = Animal()
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
@property
def perimeter(self):
return 2 * Circle.pi * self.radius
@perimeter.setter
def perimeter(self, value):
raise ReadOnlyError
@area.setter
def area(self, value):
raise ReadOnlyError
c1 = Circle(10)
print(c1.area, c1.perimeter)
5.写一个扑克游戏类, 要求拥有发牌和洗牌的功能(具体的属性和其他功能自己根据实际情况发挥)
class PokerNum(Enum):
Three = (3, '3')
Four = (4, '4')
Five = (5, '5')
Six = (6, '6')
Seven = (7, '7')
Eight = (8, '8')
Nine = (9, '9')
Ten = (10, '10')
J = (11, 'J')
Q = (12, 'Q')
K = (13, 'K')
A = (14, 'A')
Two = (15, '2')
Joker_S = (16, 'Joker')
Joker_B = (17, 'JOKER')
# print(PokerNum.J, PokerNum.J.value)
# # # 获取当前枚举类中所有的数据
# for item in PokerNum.__members__.items():
# print(item, type(item[1]))
class Poker:
def __init__(self, color: str, num: PokerNum):
self.color = color # ♥、♠、♣、♦
self.num = num # 2-10,J,Q,K,A; 大王、小王
def __repr__(self):
return '{}{}'.format(self.color, self.num.value[1])
# 让Poker对象可以比较大小(>)
# p1 > p2 -> p1.__gt__(p2)
def __gt__(self, other):
return self.num.value[0] > other.num.value[0]
class PokerGame:
def __init__(self):
# 一副牌
self.pokers = []
# 创建牌
nums = PokerNum.__members__.items()
colors = ['♥', '♠', '♣', '♦']
for num in nums:
print('>>>')
print(num)
print(num[1])
if num[1] == PokerNum.Joker_S or num[1] == PokerNum.Joker_B:
continue
for color in colors:
# 创建牌对象
p = Poker(color, num[1])
self.pokers.append(p)
self.pokers.append(Poker('', PokerNum.Joker_S))
self.pokers.append(Poker('', PokerNum.Joker_B))
# print(self.pokers)
def __shuffle(self):
# 方法一: 转换成集合
# print(set(self.pokers))
# 方法二: random.shuffle(列表)
shuffle(self.pokers)
print(self.pokers)
def deal(self):
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 = PokerGame()
# game.shuffle()
print(game.deal())
print(game.deal())
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):
# 1.读歌词文件中的内容
with open('files/'+self.__song_name+'.lrc', 'r', encoding='utf-8') as f: # 歌词文件要自行添加
while True:
line_content = f.readline()
if not line_content:
break
# 将时间和词分离
lines = line_content.split(']')
word = lines[-1]
for time in lines[:-1]:
lyric = Lyric()
lyric.time = time
lyric.word = word
self.__lyrics.append(lyric)
# 对歌词进行排序
self.__lyrics.sort(reverse=True)
# print(self.__lyrics)
print('解析歌词')
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('蓝莲花')
# l1.analysis_file()
print(l1.get_lyric(100))
print(l1.get_lyric(120))