1.建立一個汽車類Auto剧浸,包括輪胎個數(shù),汽車顏色盛卡,車身重量,速度等屬性筑凫,并通過不同的構(gòu)造方法創(chuàng)建實例滑沧。至少要求 汽車能夠加速 減速 停車。 再定義一個小汽車類CarAuto 繼承Auto 并添加空調(diào)巍实、CD屬性滓技,并且重新實現(xiàn)方法覆蓋加速、減速的方法
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.創(chuàng)建一個Person類棚潦,添加一個類字段用來統(tǒng)計Perosn類的對象的個數(shù)
class Person:
count = 0
def __init__(self):
Person.count += 1
p1 = Person()
p2 = Person()
p3 = Person()
print(Person.count)
3.創(chuàng)建一個動物類令漂,擁有屬性:性別、年齡丸边、顏色叠必、類型 ,
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.寫一個圓類妹窖, 擁有屬性半徑纬朝、面積和周長;要求獲取面積和周長的時候的時候可以根據(jù)半徑的值把對應(yīng)的值取到骄呼。但是給面積和周長賦值的時候共苛,程序直接崩潰,并且提示改屬性不能賦值
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.解析指定的歌詞文件的內(nèi)容 2.按時間顯示歌詞 提示:歌詞文件的內(nèi)容一般是按下面的格式進(jìn)行存儲的隅茎。歌詞前面對應(yīng)的是時間,在對應(yīng)的時間點可以顯示對應(yīng)的歌詞
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)