1.建立一个汽车类Auto,包括轮胎个数,汽车颜色,车身重量,速度等属性,并通过不同的构造方法创建实例。至少要求 汽车能够加速 减速 停车。 再定义一个小汽车类CarAuto 继承Auto 并添加空调、CD属性,并且重新实现方法覆盖加速、减速的方法
class Auto:
def __init__(self, color='red', weight=60, speed=120, wheel_c=4):
self.wheel_c = wheel_c
self.color = color
self.weight = weight
self.speed = speed
def speed_up(self, up):
self.speed += up
def speed_down(self, down):
self.speed -= down
def stop(self):
self.speed = 0
class AutoCar(Auto):
def __init__(self, color, weight, cd=True, air_con=True, speed=120, wheel_c=4):
super().__init__(color, weight)
self.cd = cd
self.air_con = air_con
def speed_up(self, up):
self.speed += up
def speed_down(self, down):
self.speed -= down
car1 = AutoCar('red', 1000, speed=80)
car1.speed_up(20)
print(car1.speed)
2.创建一个Person类,添加一个类字段用来统计Perosn类的对象的个数
class Person:
count = 0
def __init__(self):
Person.count += 1
p1 = Person()
p2 = Person()
p3 = Person()
print(Person.count)
3.创建一个动物类,拥有属性:性别、年龄、颜色、类型 ,
class Animal:
def __init__(self, gender, age, color, type):
self.gender = gender
self.age = age
self.color = color
self.type = type
def __str__(self):
return '/%s的对象:性别-%s 年龄:%s 颜色:%s 类型:%s/' % (self.__class__.__name__, self.gender, self.age, self.color, self.type)
dog = Animal('male', 5, 'red', 'dog')
print(dog)
4.写一个圆类, 拥有属性半径、面积和周长;要求获取面积和周长的时候的时候可以根据半径的值把对应的值取到。但是给面积和周长赋值的时候,程序直接崩溃,并且提示改属性不能赋值
from math import pi
class MyError(Exception):
def __str__(self):
return 'this attribute can\'t be changed'
class Circle:
def __init__(self, r):
self.r = r
self._C = 2*pi*r
self._S = pi*r**2
@property
def C(self):
return self._C
@C.setter
def C(self, value):
raise MyError
@property
def S(self):
return self._S
@S.setter
def S(self, value):
raise MyError
c1 = Circle(4)
print(c1.S)
print(c1.C)
c1.S = 30
5.(尝试)写一个类,其功能是:1.解析指定的歌词文件的内容 2.按时间显示歌词 提示:歌词文件的内容一般是按下面的格式进行存储的。歌词前面对应的是时间,在对应的时间点可以显示对应的歌词
class Player:
def __init__(self, path):
self.path = path
self._time = None
self.get_file()
def get_file(self):
with open(self.path, 'r', encoding='utf-8') as f:
content = f.readlines()
content = list((line.strip() for line in content))
time_maps = []
for line in content:
test = line.split(']')
words = test[-1]
times = list((e.strip(']').strip('[') for e in test[:-1]))
for time in times:
time_maps.append({'time': time, 'words': words})
time_maps.sort(key=lambda element: element['time'])
self.time_maps = time_maps
@property
def time(self):
return self._time
@time.setter
def time(self, value):
for index in range(len(self.time_maps)):
if index == len(self.time_maps)-2:
break
if value > self.time_maps[index]['time'] and value < self.time_maps[index+1]['time']:
print(self.time_maps[index]['words'])
p1 = Player('song.txt')
p1.time = '00:00.90'
print(p1.time_maps)