1.建立一个汽车类Auto,包括轮胎个数,汽车颜色,车身重量,速度等属性,并通过不同的构造方法创建实例。至少要求 汽车能够加速 减速 停车。 再定义一个小汽车类CarAuto 继承Auto 并添加空调、CD属性,并且重新实现方法覆盖加速、减速的方法
class ModifyError(Exception):
def __str__(self):
return '值不应该修改!'
class Auto:
def __init__(self, wheels: int, color: str, weight: int, speed=0):
self.wheels = wheels
self.color = color
self.weight = weight
self.speed = speed
self._tip = 0
@property
def tip(self):
return self._tip
@tip.setter
def tip(self, value):
raise ModifyError
def accelerate(self, num: int):
self.speed += num
self._tip = 1
return self
def moderate(self, num: int):
self.speed -= num
self._tip = 2
return self
def park(self):
self.speed = 0
return self
def tip_speed(self):
if not self.speed:
print('未行驶,停在原地')
elif not self._tip:
print('开始以{}公里/小时的速度向前行驶'.format(self.speed))
elif self._tip == 1:
print('加速,以{}公里/小时的速度向前行驶'.format(self.speed))
elif self._tip == 2:
print('减速,以{}公里/小时的速度向前行驶'.format(self.speed))
elif self._tip == 3:
print('限速!!!以{}公里/小时的速度向前行驶'.format(self.speed))
class CarAuto(Auto):
def __init__(self, wheels=4, color='white', weight=1500, speed=0, air_conditioner=False, cd=False):
super(CarAuto, self).__init__(wheels, color, weight, speed)
self._air_conditioner = air_conditioner
self._cd = cd
@property
def air_conditioner(self):
return self._air_conditioner
@air_conditioner.setter
def air_conditioner(self, value):
raise ModifyError
@property
def cd(self):
return self._cd
@cd.setter
def cd(self, value):
raise ModifyError
def accelerate(self, num: int):
super(CarAuto, self).accelerate(num)
if self.speed >= 100:
self.speed = 100
self._tip = 3
return self
def moderate(self, num: int):
super(CarAuto, self).moderate(num)
if self.speed <= 20:
self.speed = 20
self._tip = 3
return self
auto1 = Auto(4, 'black', 1650)
auto1.tip_speed()
auto1.speed = 60
auto1.tip_speed()
auto1.accelerate(5).tip_speed()
auto1.moderate(2).tip_speed()
auto1.park().tip_speed()
# auto1.tip = 2 # __main__.ModifyError: 值不应该修改!
print('========================================================')
car1 = CarAuto(True, True)
car1.tip_speed()
car1.accelerate(22).tip_speed()
car1.accelerate(88).tip_speed()
car1.moderate(2).tip_speed()
car1.moderate(90).tip_speed()
car1.park().tip_speed()
# car1.cd = False # __main__.ModifyError: 值不应该修改!
# car1.air_conditioner = False # __main__.ModifyError: 值不应该修改!
"""
未行驶,停在原地
开始以60公里/小时的速度向前行驶
加速,以65公里/小时的速度向前行驶
减速,以63公里/小时的速度向前行驶
未行驶,停在原地
========================================================
未行驶,停在原地
加速,以22公里/小时的速度向前行驶
限速!!!以100公里/小时的速度向前行驶
减速,以98公里/小时的速度向前行驶
限速!!!以20公里/小时的速度向前行驶
未行驶,停在原地
"""
2.创建一个Person类,添加一个类字段用来统计Perosn类的对象的个数
class ValueOfNumError(Exception):
def __str__(self):
return 'only choice between 0 and 1'
class AgeError(Exception):
def __str__(self):
return 'age should exits between 0 and 200'
class Person:
count = 0
def __init__(self, name: str, age: int, gender: int):
self.name = name
if 0 <= age <= 200:
self._age = age
else:
raise AgeError
if not gender or gender == 1:
self._gender = gender
else:
raise ValueOfNumError
self.statistics()
@property
def gender(self):
if not self._gender:
return '男'
elif self._gender == 1:
return '女'
@gender.setter
def gender(self, value: int):
if not value or value == 1:
self._gender = value
else:
raise ValueOfNumError
@property
def age(self):
return self._age
@age.setter
def age(self, value: int):
if 0 <= value <= 200:
self._age = value
else:
raise AgeError
@classmethod
def statistics(cls):
cls.count += 1
p1 = Person('a1', 18, 1)
print(p1.gender)
# p1.gender = 3 # __main__.ValueOfNumError: only choice between 0 and 1
# p1.age = -1 # __main__.AgeError: age should exits between 0 and 200
# p2 = Person('a2', 19, 2) # __main__.ValueOfNumError: only choice between 0 and 1
p2 = Person('a2', 19, 0)
print(p2.gender)
print(Person.count) # 2
p3 = Person('a3', 19, 0)
print(Person.count) # 3
3.创建一个动物类,拥有属性:性别、年龄、颜色、类型 ,
要求打印这个类的对象的时候以'/XXX的对象: 性别-? 年龄-? 颜色-? 类型-?/' 的形式来打印
class RangeError(Exception):
def __str__(self):
return '0 or 1 , but not other'
class AgeError(Exception):
def __str__(self):
return 'age >= 0 , not age < 0'
class Animal:
def __init__(self, sex: int, color: str, kind: str, age=0):
if not sex or sex == 1:
self._sex = sex
else:
raise RangeError
self.color = color
self.kind = kind
if age >= 0:
self._age = age
else:
raise AgeError
@property
def sex(self):
if not self._sex:
return '公'
if self._sex == 1:
return '母'
raise RangeError
@sex.setter
def sex(self, value: int):
self._sex = value
@property
def age(self):
if 0 <= self._age:
return self._age
raise AgeError
@age.setter
def age(self, value: int):
self._age = value
def __str__(self):
return '/{}的对象: 性别-{} 年龄-{} 颜色-{} 类型-{}/'.\
format(self.__class__.__name__, self.sex, self.age, self.color, self.kind)
dog1 = Animal(0, 'black', '二哈', 5)
print(dog1)
"""
/Animal的对象: 性别-公 年龄-5 颜色-black 类型-二哈/
"""
4.写一个圆类, 拥有属性半径、面积和周长;要求获取面积和周长的时候的时候可以根据半径的值把对应的值取到。但是给面积和周长赋值的时候,程序直接崩溃,并且提示改属性不能赋值
import math
class UnchangedError(Exception):
def __str__(self):
return '无法赋值'
class Circle:
def __init__(self, radius):
cod1 = isinstance(radius, int) or isinstance(radius, float)
cod2 = (radius >= 0)
if cod1 and cod2:
self._radius = radius
else:
raise ValueError
self._area = 0
self._perimeter = 0
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
cod1 = isinstance(value, int) or isinstance(value, float)
cod2 = (value >= 0)
if cod1 and cod2:
self._radius = value
else:
raise ValueError
@property
def area(self):
self._area = math.pi * math.pow(self._radius, 2)
return self._area
@area.setter
def area(self, value):
raise UnchangedError
@property
def perimeter(self):
self._perimeter = 2 * math.pi * self._radius
return self._perimeter
@perimeter.setter
def perimeter(self, value):
raise UnchangedError
c1 = Circle(3)
print('面积:%.2f,周长:%.2f' % (c1.area, c1.perimeter)) # 面积:28.27,周长:18.85
# c1.radius = -1 # raise ValueError
# c1.radius = 'abc' # raise ValueError
# c1.area = 2 # __main__.UnchangedError: 无法赋值
# c1.perimeter = 3 # __main__.UnchangedError: 无法赋值
5.写一个扑克类, 要求拥有发牌和洗牌的功能(具体的属性和其他功能自己根据实际情况发挥)
import random
class Player:
def __init__(self, number: int):
if 0 < number <= 8:
self.number = number
else:
raise ValueError
self.has_poker = {}
for x in range(number):
key = 'player' + str(x+1)
self.has_poker.setdefault(key, [])
class Poker:
def __init__(self, players=None):
self.players = players
self.pokers = []
self._ok = 0
@property
def ok(self):
if not self._ok:
return '进行中....'
else:
return '完成'
def shuffle_pokers(self):
nums = ['A', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
kinds = ['♥', '♠', '♣', '◆']
two = ['大王', '小王']
for kind in kinds:
for num in nums:
poker = kind + num
self.pokers.append(poker)
self.pokers += two
random.shuffle(self.pokers)
self.pokers = iter(self.pokers)
def given_pokers(self):
# 洗牌
print('洗牌.......')
print(self.ok)
self.shuffle_pokers()
self._ok = 1
print(self.ok) # 完成
print('发牌.......')
self._ok = 0
print(self.ok)
count = 54 // self.players.number
for _ in range(count):
for key in self.players.has_poker:
self.players.has_poker[key].append(next(self.pokers))
self._ok = 1
print(self.ok) # 完成
return self.players
@staticmethod
def inter_view(end_players):
print('系统内部查看玩家牌数')
if end_players.has_poker:
for key in end_players.has_poker:
print(end_players.has_poker[key])
return print('显示完成\n')
return print('没有结果')
player1 = Player(4)
poker1 = Poker(player1)
res = poker1.given_pokers()
poker1.inter_view(res)
player1 = Player(3)
poker1 = Poker(player1)
res = poker1.given_pokers()
poker1.inter_view(res)
"""
洗牌.......
进行中....
完成
发牌.......
进行中....
完成
系统内部查看玩家牌点
['◆Q', '♣10', '♥5', '◆2', '♣9', '♠4', '◆4', '◆10', '◆5', '♣8', '♠8', '◆A', '◆9']
['♣J', '♣1', '♠1', '♠10', '♠7', '◆1', '♥4', '小王', '♥9', '♣3', '♥1', '♠5', '♥J']
['♥6', '◆8', '♠9', '◆K', '♥K', '大王', '♠2', '♣4', '♥2', '♠J', '♠A', '♠K', '♥7']
['♥A', '◆7', '♣6', '♣7', '♣Q', '♠3', '♠6', '♣5', '♣2', '◆3', '♥3', '◆J', '♥10']
显示完成
洗牌.......
进行中....
完成
发牌.......
进行中....
完成
系统内部查看玩家牌点
['◆1', '♥8', '♠3', '◆A', '♥4', '◆3', '大王', '◆7', '♥K', '♥10', '◆8', '♥J', '◆4', '♠8', '♣9', '♣3', '◆6', '◆10']
['♠9', '♣K', '♠4', '♣J', '◆9', '◆5', '♥5', '♣6', '♠7', '♠6', '♠Q', '◆K', '♠10', '小王', '♣1', '♥2', '♣Q', '♣10']
['◆Q', '♣4', '◆J', '♣7', '♥A', '♣8', '♠5', '♥Q', '♠1', '♣2', '♠2', '♣A', '♠K', '♥6', '◆2', '♥1', '♥9', '♥7']
显示完成
"""
6.(尝试)写一个类,其功能是:1.解析指定的歌词文件的内容 2.按时间显示歌词 提示:歌词文件的内容一般是按下面的格式进行存储的。歌词前面对应的是时间,在对应的时间点可以显示对应的歌词
song.json文件
[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 json
import re
import time
class Song:
def __init__(self):
with open('song.json', 'r', encoding='utf-8') as f:
content = f.read()
song = json.loads(content)
self.song = song
self.dict_song = {}
self.turn_song()
def turn_song(self):
for lyric in self.song:
list1 = re.findall(r'\d+:\d+.\d+', lyric)
value = re.sub(r'\[(\d+:\d+.\d+)*\]', '', lyric)
for key in list1:
self.dict_song.setdefault(key, value)
new_keys = sorted(self.dict_song)
copy1 = {}
for x in new_keys:
copy1.setdefault(x, self.dict_song[x])
self.dict_song = copy1
for x in self.dict_song:
print(x, self.dict_song[x])
def input_time(self):
is_on = True
while is_on:
time1 = input('查询歌词请输入时间(格式是00:50.22):').replace(' ', '')
pre = None
for key in self.dict_song:
if key > time1:
break
pre = key
print(self.dict_song[pre]) if pre else print(pre)
is_on = input('是否结束?结束请按(y),继续按其他任意键既可')
is_on = False if is_on == 'y' else True
answer = input('是否选择播放歌曲模式,是请按(y),继否按其他任意键既可')
if answer == 'y':
self.play_song()
def play_song(self):
pre = 0
for key in self.dict_song:
print(self.dict_song[key])
now = (int(key[:2]) * 60 + float(key[3:]))
suspend = now - pre
pre = now
time.sleep(suspend)
print('END~~~')
song1 = Song()
song1.input_time()
"""
00:00.20 蓝莲花
00:00.80 没有什么能够阻挡
00:06.53 你对自由地向往
00:11.59 天马行空的生涯
00:16.53 你的心了无牵挂
00:21.95 穿过幽暗地岁月
00:26.83 也曾感到彷徨
00:32.30 当你低头地瞬间
00:37.16 才发觉脚下的路
00:42.69 心中那自由地世界
00:47.58 如此的清澈高远
00:52.72 盛开着永不凋零
00:57.47 蓝莲花
01:50.22 穿过幽暗地岁月
01:55.46 也曾感到彷徨
02:00.60 当你低头地瞬间
02:05.72 才发觉脚下的路
02:11.27 穿过幽暗地岁月
02:16.51 也曾感到彷徨
02:21.81 当你低头地瞬间
02:26.79 才发觉脚下的路
02:32.17 心中那自由地世界
02:37.20 如此的清澈高远
02:42.32 盛开着永不凋零
02:47.83 蓝莲花
查询歌词请输入时间(格式是00:50.22):02.47.83
也曾感到彷徨
是否结束?结束请按(y),继续按其他任意键既可
查询歌词请输入时间(格式是00:50.22):02:47.83
蓝莲花
是否结束?结束请按(y),继续按其他任意键既可y
是否选择播放歌曲模式,是请按(y),继否按其他任意键既可y
蓝莲花
没有什么能够阻挡
你对自由地向往
天马行空的生涯
你的心了无牵挂
穿过幽暗地岁月
也曾感到彷徨
当你低头地瞬间
才发觉脚下的路
心中那自由地世界
如此的清澈高远
盛开着永不凋零
蓝莲花
穿过幽暗地岁月
也曾感到彷徨
当你低头地瞬间
才发觉脚下的路
穿过幽暗地岁月
也曾感到彷徨
当你低头地瞬间
才发觉脚下的路
心中那自由地世界
如此的清澈高远
盛开着永不凋零
蓝莲花
END~~~
"""