1.建立一个汽车类Auto,包括轮胎个数,汽车颜色,车身重量,速度等属性,并通过不同的构造方法创建实例。至少要求 汽车能够加速 减速 停车。 再定义一个小汽车类CarAuto 继承Auto 并添加空调、CD属性,并且重新实现方法覆盖加速、减速的方法 。
class Auto:
def __init__(self, reel, color, weight, vlocity):
self.reel = reel
self.color = color
self.weight = weight
self.vlocity = vlocity
@staticmethod
def speed_up():
print("汽车加速!")
@staticmethod
def brake():
print("减速!")
@staticmethod
def park():
print("停车!")
class CarAuto(Auto):
def __init__(self, air_conditional, CD):
super().__init__(4, "green", "2T", 90)
self.air_conditional = air_conditional
self.CD = CD
def speed_up(self):
print("%s汽车加速!" % self.reel)
def brake(self):
print("%s车减速!" % self.color)
super().brake()
car = Auto(4, "red", "2T", "80")
print(car.__dict__) # {'reel': 4, 'color': 'red', 'weight': '2T', 'vlocity': '80'}
carauto = CarAuto(True, True)
print(carauto.__dict__)
# {'reel': 4, 'color': 'green', 'weight': '2T', 'vlocity': 90, 'air_conditional': True, 'CD': True}
print(car.brake()) # 减速!
print(carauto.brake()) # green车减速!\n 减速!
2.创建一个Person类,添加一个类字段用来统计Perosn类的对象的个数
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
Person.count += 1
# 创建多少次对象,就要初始化多少次init函数,就要自动调用多少次init函数
print("已经创建了%d个对象" % Person.count)
count = 0
p1 = Person("小明", 18) # 已经创建了1个对象
p2 = Person("小化", 15) # 已经创建了2个对象
print(p1.__dict__) # {'name': '小明', 'age': 18}
3.创建一个动物类,拥有属性:性别、年龄、颜色、类型 ,
要求打印这个类的对象的时候以'/XXX的对象: 性别-? 年龄-? 颜色-? 类型-?/' 的形式来打印
class Animal:
def __init__(self, type, gender, age, color):
self.type = type
self.gender = gender
self.age = age
self.color = color
def __str__(self):
return "/{}的对象: 性别-{} 年龄-{} 颜色-{} 类型-{}/".format(Animal.__name__, self.gender, self.age, self.color, self.type)
animal = Animal("Hasky", "male", 8, "red")
print(animal)
# /Animal的对象: 性别-male 年龄-8 颜色-red 类型-Hasky/
- 写一个圆类, 拥有属性半径、面积和周长;要求获取面积和周长的时候的时候可以根据半径的值把对应的值取到。但是给面积和周长赋值的时候,程序直接崩溃,并且提示改属性不能赋值
class WriteError(Exception):
def __str__(self):
return "修改只读属性"
from math import pi
class Circle:
def __init__(self, r):
self.r = r
self._area = 0
self._perimeter = 0
@property
def area(self):
self._area = self.r ** 2 * pi
return self._area
@area.setter
def area(self, value):
raise WriteError
@property
def perimeter(self):
self._perimeter = self.r * 2 * pi
return self._perimeter
@perimeter.setter
def perimeter(self, value):
raise WriteError
circle = Circle(4)
circle.r = 6
circle.area
circle.perimeter
print(circle.__dict__)
# {'r': 6, '_area': 113.09733552923255, '_perimeter': 37.69911184307752}
circle.r = 5
circle.area
circle.perimeter
print(circle.__dict__)
# {'r': 5, '_area': 78.53981633974483, '_perimeter': 31.41592653589793}
# circle.area=9 #__main__.WriteError: 修改只读属性
5.写一个扑克类, 要求拥有发牌和洗牌的功能(具体的属性和其他功能自己根据实际情况发挥)
import random
class Poker:
def __init__(self, pattern):
self.pattern = pattern
@staticmethod
def getcards():
cards = []
for i in ["♠", "♥", "♦", "♣"]:
for j in ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]:
dict1 = {}
dict1[i] = j
cards.append(dict1)
cards.append({"JOKER": "JOKER"})
cards.append({"joker": "joker"})
return cards
@staticmethod
def shuffle():
p = Poker.getcards()
random.shuffle(p)
return p
def putcards(self):
person1 = []
person2 = []
person3 =[]
iter1 = iter(Poker.shuffle())
for i in range(17):
person1.append(next(iter1))
person2.append(next(iter1))
person3.append(next(iter1))
person3.append(next(iter1))
person3.append(next(iter1))
person3.append(next(iter1))
return person1, person2, person3
def main():
poker = Poker("green")
cards = poker.putcards( )
print("农名1的牌:", cards[0])
print("农名2的牌:", cards[1])
print("地主的牌:", cards[2])
# 农名1的牌: [{'♥': '4'}, {'♦': '4'}, {'♠': '9'}, {'♥': 'K'}, {'♣': '9'}, {'♣': 'A'}, {'♠': 'J'}, {'♥': 'Q'}, {'♦': 'Q'}, {'♣': '7'}, {'♣': '3'}, {'♥': '2'}, {'♣': '8'}, {'♦': 'K'}, {'♥': '7'}, {'♣': '6'}, {'♦': '3'}]
# 农名2的牌: [{'♥': 'J'}, {'♠': '8'}, {'JOKER': 'JOKER'}, {'♦': '2'}, {'♠': 'K'}, {'♥': '9'}, {'♥': '8'}, {'♦': 'A'}, {'♣': '2'}, {'♦': '9'}, {'joker': 'joker'}, {'♠': '10'}, {'♥': '5'}, {'♠': '5'}, {'♠': 'Q'}, {'♦': 'J'}, {'♠': '2'}]
# 地主的牌: [{'♥': 'A'}, {'♦': '10'}, {'♥': '6'}, {'♠': '3'}, {'♠': 'A'}, {'♣': 'J'}, {'♣': 'Q'}, {'♠': '6'}, {'♥': '10'}, {'♦': '7'}, {'♦': '8'}, {'♣': 'K'}, {'♦': '6'}, {'♣': '4'}, {'♠': '4'}, {'♣': '5'}, {'♣': '10'}, {'♠': '7'}, {'♥': '3'}, {'♦': '5'}]
if __name__ == '__main__':
main()
- (尝试)写一个类,其功能是:1.解析指定的歌词文件的内容 2.按时间显示歌词
提示:歌词文件的内容一般是按下面的格式进行存储的。 歌词前面对应的是时间,在对应的时间点可以显示对应的歌词
import time
class Lyric:
# 分割单条歌词的时间和歌词
def time_split(lyrics_line):
time_line = lyrics_line.split("]")
dict1 = {}
# 按照“】”将单句歌词切片
# ['[02:11.27', '[01:50.22', '[00:21.95', '穿过幽暗地岁月\n']
# 切片之后再将每个字符串切片,之后将时间点的时间戳计算出来,分钟*60+秒可以得到歌词显示的时间戳
for index in range(len(time_line) - 1):
# 取出单条歌词的切片列表,做出【时间:歌词】的字典
minutes = float(time_line[index][1:3])
# 取出分钟时间
seconds = float(time_line[index][4:])
# 取出秒的时间
time_point = minutes * 60 + seconds
# 取出唯一的时间戳
dict1[time_point] = time_line[-1][:-1]
# 以唯一的时间戳作为键,歌词作为值生成字典
return dict1
# 解析歌词
def an_lyric(lyric_dict):
time_line = sorted(lyric_dict)
# 获取当前时间作为起始时间戳
time_point = time.time()
point = 0 # 取为时间轴的元素
while True:
if time.time() > time_point + time_line[point]:
# 如果程序运行时间大于自定义时间戳加时间差,答应时间差歌词
print(lyric_dict[time_line[point]])
point += 1
if point >= len(lyric_dict): # 如果打印歌词的次数大于字典的长度,就跳出循环。
break
def main():
lyric = Lyric
lyric_dict = {}
with open("lyrics.txt", "r", encoding="utf-8") as file:
files = file.readlines()
for lyric_line in files:
# 调用歌词类的分解歌词方法
lyric.time_split(lyric_line)
# 得到单条歌词生成的键值对并使其加入歌词字典
lyric_dict.update(lyric.time_split(lyric_line))
lyric.an_lyric(lyric_dict)
if __name__ == '__main__':
main()
# 蓝莲花
# 没有什么能够阻挡
# 你对自由地向往
# 天马行空的生涯
# 你的心了无牵挂
# 穿过幽暗地岁月
# 也曾感到彷徨
# 当你低头地瞬间
# 才发觉脚下的路
# 心中那自由地世界
# 如此的清澈高远
# 盛开着永不凋零
# 蓝莲花
# 穿过幽暗地岁月
# 也曾感到彷徨
# 当你低头地瞬间
# 才发觉脚下的路
# 穿过幽暗地岁月
# 也曾感到彷徨
# 当你低头地瞬间
# 才发觉脚下的路
# 心中那自由地世界
# 如此的清澈高远
# 盛开着永不凋零
# 蓝莲花