1. 建立一个汽车类Auto,包括轮胎个数,汽车颜色,车身重量,速度等属性,并通过不同的构造方法创建实例。至少要求 汽车能够加速 减速 停车。 再定义一个小汽车类CarAuto 继承Auto 并添加空调、CD属性,并且重新实现方法覆盖加速、减速的方法
class CorrectType(Exception):
"""类型错误异常"""
def __str__(self):
return 'Wrong type!'
class WriteError(Exception):
"""只读异常"""
def __str__(self):
return 'Modify read-only properties!'
class Auto:
"""汽车类"""
def __init__(self, tires_num, color, weight, speed=0):
"""
:param tires_num: 轮胎个数
:param color: 汽车颜色
:param weight: 车身重量
:param speed: 起始速度
"""
self._tires_num = self.tires_num = tires_num
self._color = color
self.weight = weight
if not (isinstance(speed, int) or isinstance(speed, float)) or speed < 0:
raise CorrectType
else:
self._speed = speed
@property
def tires_num(self):
return self._tires_num
@tires_num.setter
def tires_num(self, value):
if not isinstance(value, int) or value <= 0:
raise CorrectType
self._tires_num = value
@property
def color(self):
return self._tires_num
@color.setter
def color(self, value):
if not isinstance(value, str):
raise CorrectType
self._tires_num = value
@property
def weight(self):
return self._tires_num
@weight.setter
def weight(self, value):
if not Auto.is_num(value):
raise CorrectType
self._tires_num = value
@property
def speed(self):
return self._speed
@speed.setter
def speed(self, value):
"""速度只能通过加速/减速/停车方法改变"""
raise WriteError
def accelerate(self, sp):
"""加速"""
if not Auto.is_num(sp):
raise CorrectType
old_speed = self.speed
self._speed += sp
print('The auto is accelerating({} -> {}), the current speed is {} km/h.'
.format(old_speed, self.speed, self.speed))
def decelerate(self, sp):
"""减速"""
if not Auto.is_num(sp):
raise CorrectType
old_speed = self.speed
self._speed = self._speed - sp if self._speed >= sp else 0
print('The auto is decelerating({} -> {}), the current speed is {} km/h.'
.format(old_speed, self.speed, self.speed))
def stop(self):
self._speed = 0
print('The auto stopped, the current speed is {} km/h'.format(self.speed))
@staticmethod
def is_num(value):
"""是否是正数"""
return isinstance(value, int) or isinstance(value, float) or value > 0
def __repr__(self):
return ''.join(['<', str(self.__dict__)[1:-1], '>'])
class CarAuto(Auto):
"""小汽车类"""
def __init__(self, tires_num, color, weight, speed=0, air_conditioning=False, cd=False):
"""
:param tires_num: 轮胎个数
:param color: 汽车颜色
:param weight: 车身重量
:param speed: 起始速度
:param air_conditioning: 是否有空调
:param cd: 是否有CD
"""
super().__init__(tires_num, color, weight, speed)
self.air_conditioning = air_conditioning
self.cd = cd
def accelerate(self, sp):
old_speed = self.speed
self._speed += sp
print('The car is accelerating({} -> {}), the current speed is {} km/h.'
.format(old_speed, self.speed, self.speed))
def decelerate(self, sp):
"""减速"""
old_speed = self.speed
self._speed = self._speed - sp if self._speed >= sp else 0
print('The car is decelerating({} -> {}), the current speed is {} km/h.'
.format(old_speed, self.speed, self.speed))
auto1 = Auto(4, 'black', 300)
auto1.accelerate(20)
# The auto is accelerating(0 -> 20), the current speed is 20 km/h.
auto1.decelerate(10)
# The auto is decelerating(20 -> 10), the current speed is 10 km/h.
auto1.stop()
# The auto stopped, the current speed is 0 km/h
car1 = CarAuto(4, 'red', 200, air_conditioning=True)
car1.accelerate(40)
# The car is accelerating(0 -> 40), the current speed is 40 km/h.
car1.decelerate(20)
# 1The car is decelerating(40 -> 20), the current speed is 20 km/h.
2. 创建一个Person类,添加一个类字段用来统计Person类的对象的个数
class Person:
count = 0
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
Person.count += 1
def __repr__(self):
return ''.join(['<', str(self.__dict__)[1:-1], '>'])
p1 = Person('Lina', 19, 'female')
print(Person.count) # 1
p2 = Person('Jack', 18, 'male')
print(Person.count) # 1
p3 = Person('Kin', 20, 'male')
print(Person.count) # 1
3. 创建一个动物类,拥有属性:性别、年龄、颜色、类型 ,
要求打印这个类的对象的时候以'/XXX的对象: 性别-? 年龄-? 颜色-? 类型-?/' 的形式来打印
class Animal:
def __init__(self, gender, age, color, species):
self.gender = gender
self.age = age
self.color = color
self.species = species
def __repr__(self):
"""/XXX的对象: 性别-? 年龄-? 颜色-? 类型-?/'"""
return '/{}的对象: 性别-{} 年龄-{} 颜色-{} 类型-{}/' \
.format(self.__class__.__name__, self.gender, self.age, self.color, self.species)
class Cat(Animal):
pass
class Dog(Animal):
pass
a1 = Animal('公', 3, '白色', '哺乳动物')
print(a1) # /Animal的对象: 性别-公 年龄-3 颜色-白色 类型-哺乳动物/
c1 = Cat('母', 2, '灰白相间', '布偶猫')
print(c1) # /Cat的对象: 性别-母 年龄-2 颜色-灰白相间 类型-布偶猫/
d1 = Dog('公', 1, '黑', '哈士奇')
print(d1) # /Dog的对象: 性别-公 年龄-1 颜色-黑 类型-哈士奇/
4. 写一个圆类, 拥有属性半径、面积和周长;要求获取面积和周长的时候的时候可以根据半径的值把对应的值取到。但是给面积和周长赋值的时候,程序直接崩溃,并且提示改属性不能赋值
class Circle:
pi = 3.141592653589793
def __init__(self, radius):
self.radius = radius
self._area = Circle.pi * self.radius ** 2
self._perimeter = 2 * Circle.pi * self.radius
@property
def area(self):
self._area = Circle.pi * self.radius ** 2
return self._area
@area.setter
def area(self, value):
raise WriteError
@property
def perimeter(self):
self._perimeter = 2 * Circle.pi * self.radius
return self._perimeter
@perimeter.setter
def perimeter(self, value):
raise WriteError
def __repr__(self):
return '<radius: {}, area: {}, perimeter: {}>'\
.format(self.radius, self.area, self.perimeter)
c1 = Circle(10)
print(c1) # <radius: 10, area: 314.1592653589793, perimeter: 62.83185307179586>
c1.area = 100 # __main__.WriteError: Modify read-only properties!
c1.perimeter = 30 # __main__.WriteError: Modify read-only properties!
c1.radius = 5
print(c1) # <radius: 5, area: 78.53981633974483, perimeter: 31.41592653589793>
5. 写一个扑克类, 要求拥有发牌和洗牌的功能(具体的属性和其他功能自己根据实际情况发挥)
from random import shuffle
class CorrectType(Exception):
"""类型错误异常"""
def __str__(self):
return 'Wrong type!'
class Poker:
__colors = ['♥️', '♠️', '♦️', '♣️']
__nums = ['3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A', '2']
def __init__(self):
self.__cards = [i for i in range(54)]
shuffle(self.__cards)
self.__top_cards = self.__cards[:3]
# 对分组的牌排序
self.__p1 = self.__p2 = self.__p3 = []
self.__p1 = Poker.__sorted_cards(self.__cards[3:20])
self.__p2 = Poker.__sorted_cards(self.__cards[20:37])
self.__p3 = Poker.__sorted_cards(self.__cards[37:])
@property
def cards(self):
return Poker.__set_cards(self.__cards)
@cards.setter
def cards(self, value):
# self.__cards = [i for i in range(54)]
# shuffle(self.__cards)
raise WriteError
@property
def top_cards(self):
return Poker.__set_cards(self.__top_cards)
@top_cards.setter
def top_cards(self, value):
raise WriteError
@property
def p1(self):
return Poker.__set_cards(self.__p1)
@p1.setter
def p1(self, value):
raise WriteError
@property
def p2(self):
return Poker.__set_cards(self.__p2)
@p2.setter
def p2(self, value):
raise WriteError
@property
def p3(self):
return Poker.__set_cards(self.__p3)
@p3.setter
def p3(self, value):
raise WriteError
@staticmethod
def __sorted_cards(cards: list):
"""数组排序"""
self_cards = sorted(cards)
return self_cards
def to_be_landlord(self):
"""叫地主阶段,共两轮,如果没有玩家叫地主,流局重新洗牌"""
times = 2
while times:
for i in range(1, 4):
player = ''.join(['p', str(i)])
choice = str(i) + input('{}是否叫地主(y/n):'.format(player))
if choice[-1] == 'y':
# 拼接属性名
player = '_Poker__' + player
# print(player)
# 动态获取当前叫地主的玩家(p1-p3)
p = getattr(self, player)
# 将顶牌加入后,该玩家手牌重写排序
setattr(self, player, Poker.__sorted_cards(p + self.__top_cards))
self.__top_cards.clear()
print('\n叫地主完成,地主为{}'.format(player[-2:]))
print(self)
return
else:
continue
times -= 1
print('无人叫地主,本局流局...\n重新发牌:')
self.__init__()
print(self)
self.to_be_landlord()
@classmethod
def __set_cards(cls, part_cards: list):
"""返回有花色和大小的展示牌组"""
part_len = len(part_cards)
out_cards = ['' for _ in range(part_len)]
for index in range(part_len):
if part_cards[index] == 52:
out_cards[index] = 'Black Joker'
elif part_cards[index] == 53:
out_cards[index] = 'Red Joker'
else:
# 按大小排
out_cards[index] = cls.__colors[part_cards[index] % 4] + cls.__nums[part_cards[index] // 4]
return out_cards
def __repr__(self):
# return 'top_cards: {}\np1: {}\np2: {}\np3: {}' \
# .format(self.__top_cards, self.__p1, self.__p2, self.__p3)
return 'top_cards: {}\np1: {}\np2: {}\np3: {}' \
.format(self.top_cards, self.p1, self.p2, self.p3) if self.__top_cards else \
'p1: {}\np2: {}\np3: {}'.format(self.p1, self.p2, self.p3)
poker = Poker()
print(poker)
poker.to_be_landlord()
'''
top_cards: ['♠️J', '♦️5', '♠️7']
p1: ['♥️4', '♣️4', '♠️5', '♣️5', '♥️6', '♥️7', '♦️7', '♠️8', '♣️8', '♥️10', '♦️J', '♥️Q', '♠️Q', '♥️K', '♠️K', '♦️K', '♠️2']
p2: ['♠️3', '♦️3', '♣️3', '♠️4', '♦️6', '♣️7', '♦️8', '♠️9', '♦️10', '♥️J', '♥️A', '♠️A', '♣️A', '♥️2', '♣️2', 'Black Joker', 'Red Joker']
p3: ['♥️3', '♦️4', '♥️5', '♠️6', '♣️6', '♥️8', '♥️9', '♦️9', '♣️9', '♠️10', '♣️10', '♣️J', '♦️Q', '♣️Q', '♣️K', '♦️A', '♦️2']
p1是否叫地主(y/n):
p2是否叫地主(y/n):
p3是否叫地主(y/n):
p1是否叫地主(y/n):y
叫地主完成,地主为p1
p1: ['♥️4', '♣️4', '♠️5', '♦️5', '♣️5', '♥️6', '♥️7', '♠️7', '♦️7', '♠️8', '♣️8', '♥️10', '♠️J', '♦️J', '♥️Q', '♠️Q', '♥️K', '♠️K', '♦️K', '♠️2']
p2: ['♠️3', '♦️3', '♣️3', '♠️4', '♦️6', '♣️7', '♦️8', '♠️9', '♦️10', '♥️J', '♥️A', '♠️A', '♣️A', '♥️2', '♣️2', 'Black Joker', 'Red Joker']
p3: ['♥️3', '♦️4', '♥️5', '♠️6', '♣️6', '♥️8', '♥️9', '♦️9', '♣️9', '♠️10', '♣️10', '♣️J', '♦️Q', '♣️Q', '♣️K', '♦️A', '♦️2']
'''
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]蓝莲花
import time
import re
class CorrectType(Exception):
"""类型错误异常"""
def __str__(self):
return 'Wrong type!'
class LyricsAnalysis:
"""解析歌词文件及显示歌词"""
def __init__(self):
self.__lyric_list = []
@property
def lyric_list(self):
return self.__lyric_list
@lyric_list.setter
def lyric_list(self, value):
raise WriteError
def analysis(self, path: str):
"""分析歌词文件"""
with open(path, 'r', encoding='utf-8') as f:
line = f.readline()
while line:
r1 = re.compile(r'(\d{2}:\d{2}\.\d{2})') # r1分离时间
# r'([\u4E00-\u9FA5A-Za-z:./-]*)(?:\n)$'
r2 = re.compile(r'(?:])(\D+)$') # r2分离歌词,匹配']'(不显示)和非数字类型
ti = r1.findall(line)
ly = r2.findall(line)
# print(ti, ly)
if ti:
for key in r1.findall(line):
key = LyricsAnalysis.__to_second(key)
value = ly[0] if ly else ''
# print(key, value)
self.__lyric_list.append([key, value])
self.__lyric_list.sort()
line = f.readline()
def show_lyrics(self, speed=0):
"""显示歌词"""
for index in range(len(self.__lyric_list) - 1):
last_time = self.__lyric_list[index][0]
this_time = self.__lyric_list[index + 1][0]
sleep_time = this_time - last_time
if sleep_time > 2:
if not index % 10:
speed = sleep_time / 15 + sleep_time / 100
else:
speed = sleep_time / 15
else:
if not index % 5:
speed = sleep_time / 45 + sleep_time / 20
else:
speed = sleep_time / 45
while sleep_time > speed:
# print(this_time - last_time)
print('\r{}\t\t{:.2f}'.format(self.__lyric_list[index][1][:-1], sleep_time), end='')
time.sleep(speed)
sleep_time -= speed
print('\r{}'.format(self.__lyric_list[-1][1]))
@staticmethod
def __to_second(str1: str):
"""字符串时间转换秒"""
r = re.compile(r'(?::)') # 分离分钟和秒
result = r.split(str1)
minute = result[0]
return int(minute) * 60 + float(result[1])