Day15 作業(yè)

  1. 建立一個汽車類Auto,包括輪胎個數(shù),汽車顏色,車身重量,速度等屬性,并通過不同的構(gòu)造方法創(chuàng)建實例。至少要求 汽車能夠加速 減速 停車。 再定義一個小汽車類CarAuto 繼承Auto 并添加空調(diào)、CD屬性,并且重新實現(xiàn)方法覆蓋加速、減速的方法
"""______lxh______"""


class Auto:     # init方法
    def __init__(self, color, weight, speed, tyr_num):
        self.tyr_num = tyr_num
        self.color = color
        self.weight = weight
        self.speed = speed

    def speed_up(self):
        self.speed += 3
        print('速度增加了3碼! Speed:', self.speed)

    def speed_down(self):
        if self.speed >= 3:
            self.speed -= 3
            print('減速了3碼! Speed:', self.speed)
        elif self.speed:
            self.speed = 0
            print('車速太低, 車停了!')
        else:
            print('汽車尚未啟動!')

    def park(self):
        if self.speed:
            while True:
                if self.speed >= 8:
                    self.speed -= 8
                    print('正在剎車, Speed:', self.speed)
                else:
                    self.speed = 0
                    print('車停了!')
                    break
        else:
            print('車已經(jīng)停了!')


class Auto1:        # 構(gòu)造函數(shù)
    tyr_num = 4
    color = 'black'
    weight = '1t'
    speed = 35

    def speed_up(self):
        self.speed += 3
        print('速度增加了3碼! Speed:', self.speed)

    def speed_down(self):
        if self.speed >= 3:
            self.speed -= 3
            print('減速了3碼! Speed:', self.speed)
        elif self.speed:
            self.speed = 0
            print('車速太低, 車停了!')
        elif self.speed:
            self.speed = 0

        else:
            print('汽車尚未啟動!')

    def park(self):
        if self.speed:
            while True:
                if self.speed >= 8:
                    self.speed -= 8
                    print('正在剎車, Speed:', self.speed)
                else:
                    self.speed = 0
                    print('車停了!')
                    break
        else:
            print('車已經(jīng)停了!')


class CarAuto(Auto):    # 繼承
    def __init__(self, color, weight, speed, tyr_num, condition, cd):
        super().__init__(color, weight, speed, tyr_num)
        self.condition = condition
        self.cd = cd
        self.tyr_num = 4

    def speed_up(self):
        self.speed += 5
        print('速度增加了5碼! Speed:', self.speed)

    def speed_down(self):
        if self.speed >= 5:
            self.speed -= 5
            print('減速了5碼! Speed:', self.speed)
        elif self.speed:
            self.speed = 0
            print('車速太低, 車停了!')
        elif self.speed:
            self.speed = 0

    def play_cond(self):
        if self.condition == 'on':
            self.condition = 'off'
            print('關(guān)閉空調(diào)!')
        else:
            self.condition = 'on'
            print('打開空調(diào)!')

    def play_cd(self):
        if self.cd == 'on':
            self.cd = 'off'
            print('關(guān)閉音樂!')
        else:
            self.cd = 'on'
            print('打開音樂!')


car1 = Auto('black', '1t', 30, 4)
car2 = Auto1()

car1.speed_up()
car1.speed_down()
car1.park()

print(car2.color, car2.speed, car2.weight, car2.tyr_num)
car2.speed_up()
car2.speed_down()
car2.park()

car3 = CarAuto('black', '1t', 39, 4, 'on', 'on')
print(car3.__dict__)
car3.speed_up()
car3.speed_down()
car3.play_cd()
car3.play_cd()
car3.play_cond()
car3.play_cond()
  1. 創(chuàng)建一個Person類,添加一個類字段用來統(tǒng)計Perosn類的對象的個數(shù)
"""______lxh______"""


class Person:
    _num = 0

    def __init__(self, name, age, sex):
        self.name = name
        self.age = age
        self._sex = sex
        Person._num += 1
        print('有%d個對象!' % Person._num)

    def show(self):
        print(self.name, self.age, self._sex)

    @property
    def sex(self):
        print('性別被訪問!')
        return self.sex

    @sex.setter
    def sex(self, value):
        if value:
            raise Readonly


class Readonly(Exception):
    def __str__(self):
        return 'Readonly'


p1 = Person('小明', 20, '男')
p2 = Person('小明', 20, '男')
p3 = Person('小明', 20, '男')
  1. 創(chuàng)建一個動物類,擁有屬性:性別、年齡、顏色、類型 ,

    要求打印這個類的對象的時候以'/XXX的對象: 性別-? 年齡-? 顏色-? 類型-?/' 的形式來打印

"""______lxh______"""


class Animal:
    def __init__(self, sex, age, color, breed):
        self.sex = sex
        self.age = age
        self.color = color
        self.breed = breed

    def __str__(self):
        return '/ ' + a1.__class__.__name__ + '的對象: 性別-' + self.sex + ', 年齡-' + str(self.age) + ', 顏色-' + self.color + ', 類型-' + self.breed + ' /'


a1 = Animal('母', 3, 'yellow', '哈奇士')
print(a1)
  1. 寫一個圓類, 擁有屬性半徑、面積和周長;要求獲取面積和周長的時候的時候可以根據(jù)半徑的值把對應(yīng)的值取到。但是給面積和周長賦值的時候,程序直接崩潰,并且提示改屬性不能賦值
"""______lxh______"""


class Circle:
    pi = 3.14

    def __init__(self, radius: int):
        self.radius = radius
        self._area = self.pi * radius ** 2
        self._girth = 2 * self.pi * self.radius

    @property
    def area(self):
        return self._area

    @area.setter
    def area(self, value):
        if value:
            raise Readonly

    @property
    def girth(self):
        return self._girth

    @girth.setter
    def girth(self, value):
        if value:
            raise Readonly


class Readonly(Exception):
    def __str__(self):
        return 'Readonly123'


c1 = Circle(5)
print(c1.area)
print(c1.girth)
# c1.area = 20
  1. 寫一個撲克類, 要求擁有發(fā)牌和洗牌的功能(具體的屬性和其他功能自己根據(jù)實際情況發(fā)揮)
"""______lxh______"""

from random import shuffle


class Poker:
    _num = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
    _color = ['紅桃', '黑桃', '方塊', '梅花']
    _Joker = 'JOKER'
    _joker = 'joker'
    _pokers = []
    for n in _color:
        for c in _num:
            _pokers.append(c + n)
    _pokers.append(_Joker)
    _pokers.append(_joker)
    shuffle(_pokers)

    @classmethod
    def deal(cls):
        user1 = cls._pokers[:17]
        user2 = cls._pokers[17:34]
        user3 = cls._pokers[34:51]
        print('User1', user1)
        print('User2', user2)
        print('User3', user3)
        print('底牌:', cls._pokers[51:])

    @classmethod
    def riffle(cls):
        shuffle(cls._pokers)
        print(cls._pokers)


def main():
    p1 = Poker
    p1.deal()
    p1.riffle()
    p1.deal()


if __name__ == '__main__':
    main()
  1. (嘗試)寫一個類,其功能是:1.解析指定的歌詞文件的內(nèi)容 2.按時間顯示歌詞 提示:歌詞文件的內(nèi)容一般是按下面的格式進行存儲的。歌詞前面對應(yīng)的是時間,在對應(yīng)的時間點可以顯示對應(yīng)的歌詞
"""______lxh______"""
from time import time, sleep
import pygame


class Music:
    def __init__(self, lrc):
        self._lrc = lrc/
        self._time = 0
        self._old_time = 0

    def auto_lrc(self):     # 自動播放音樂打印歌詞
        pygame.mixer.init()
        pygame.mixer.music.load('files/Way Back Into Love.mp3')     # 加載音樂
        pygame.mixer.music.play()       # 播放音樂
        self._time = time()         # 獲得開始播放的時間戳
        for tim in self._lrc:
            while round(time() - self._time, 2) < tim:  # 根據(jù)播放時間顯示歌詞
                continue
            else:
                print(self._lrc[tim])
        sleep(12)       # 最后一句還有一段時間
        pygame.mixer.music.stop()       # 停止播放音樂

    def show_lrc(self):     # 打印指定時間的歌詞
        second = input('請輸入時間(秒):')
        sec = round(float(second), 2)
        for tim in self._lrc:
            if self._old_time < sec < tim:   # 判斷時間區(qū)間打印歌詞
                print(self._lrc[self._old_time])
                self._old_time = 0
                return
            self._old_time = tim


def main():
    lrc = {}
    path = 'files/Way.lrc'
    style = 'GBK'
    with open(path, encoding=style) as f:
        content = f.read()
        content = content.splitlines()
        content = [x for x in content if x != '']
        for lin in content:
            if lin[3] != ':' or lin[6] != '.':      # 判斷是否是說明文檔
                continue
            li = lin.split(']')
            for t in li[:-1]:
                tim = t.split(':')        # 分割時間
                lrc[round(float(tim[0][1:]) * 60 + float(tim[1]), 2)] = li[-1]    # round(num, 2) 保留小數(shù)點后兩位 存秒數(shù)
        lrc = dict(sorted(lrc.items(), key=lambda k: k[0]))

    play = Music(lrc)   # 創(chuàng)建對象
    play.auto_lrc()     # 播放音樂
    # play.show_lrc()   # 打印指定歌詞


if __name__ == '__main__':
    main()
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。