2019-08-10

作業(yè)

1.建立一個汽車類Auto,包括輪胎個數(shù),汽車顏色,車身重量,速度等屬性,

并通過不同的構(gòu)造方法創(chuàng)建實例。至少要求 汽車能夠加速 減速 停車。

再定義一個小汽車類CarAuto 繼承Auto 并添加空調(diào)、CD屬性,

并且重新實現(xiàn)方法覆蓋加速、減速的方法

import time
import sys
import math
import random
class Auto:
    def __init__(self, weight, color, speed, num_tyre=4):
        self.weight = weight
        self.color = color
        self.speed = speed
        self.num_tyre = num_tyre

    def accelerate_slow_down(self, throttle):
            if throttle == 1:
                print("油門被踩下")
                count = 1
                while True:
                    self.speed = self.speed + self.speed*(count**2)/500
                    count += 1
                    time.sleep(1)
                    print(self.speed)
                    if self.speed >= 180:
                        print("車速太快,請剎車")
                        break

            elif throttle == 0:
                    print("油門松開")
                    count = 1
                    while True:
                        self.speed = self.speed - self.speed * (count ** 2) / 200
                        count += 1
                        time.sleep(1)
                        print(self.speed)
                        if self.speed <= 20:
                            print("車速太慢了可以加點油了")
                            break
            elif throttle == 2:
                print("請減速停車")
                print("踩剎車")
                count = 1
                while True:
                    self.speed = self.speed - self.speed * (count ** 2) / 100
                    count += 1
                    time.sleep(1)
                    print(self.speed)
                    if self.speed <= 0:
                        print("車已經(jīng)停好了")
                        break

            else:
                print("勻速行駛")


p1 = Auto("3T", 'white', 60)
p1.accelerate_slow_down(2)


class CarAuto(Auto):

    def __init__(self, air, cd):
        super().__init__("3T", 'white', 80)
        self.air = air
        self.cd = cd

    def accelerate_slow_down(self, throttle):
            if throttle == 1:
                print("油門被踩下")
                count = 1
                while True:
                    self.speed = self.speed + self.speed*(count**2)/400
                    count += 1
                    time.sleep(1)
                    print(self.speed)
                    if self.speed >= 180:
                        print("車速太快,請剎車")
                        break

            elif throttle == 0:
                    print("油門松開")
                    count = 1
                    while True:
                        self.speed = self.speed - self.speed * (count ** 2) / 240
                        count += 1
                        time.sleep(1)
                        print(self.speed)
                        if self.speed <= 20:
                            print("車速太慢了可以加點油了")
                            break
            elif throttle == 2:
                print("請減速停車")
                print("踩剎車")
                count = 1
                while True:
                    self.speed = self.speed - self.speed * (count ** 2) / 120
                    count += 1
                    time.sleep(1)
                    print(self.speed)
                    if self.speed <= 0:
                        print("車已經(jīng)停好了")

            else:
                print("勻速行駛")


p2 = CarAuto(0, 1)
p2.accelerate_slow_down(1)

2.創(chuàng)建一個Person類,添加一個類字段用來統(tǒng)計Perosn類的對象的個數(shù)

print()

class Count:
    count = 0


class Person(Count):
    def __init__(self):
        Count.count += 1

    def student(self):
        Count.count += 1


p1 = Person()
p1.student()
print(p1.count)  # 2

3.創(chuàng)建一個動物類,擁有屬性:性別、年齡、顏色、類型 ,

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

print()

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

    @property
    def sex(self):
        if self._sex == 1:
            return '公'
        elif self._sex == 0:
            return '母'
        else:
            return '輸入錯誤'

    def print_type(self, name):
        print("%s的對象: 性別-%s,年齡-%s,顏色-%s,類型-%s"
              % (name, self.sex, self.age, self.color, self.type_a))
    #
    # @property
    # def sex(self):
    #     if self._sex == 1:
    #         return '公'
    #     elif self._sex == 0:
    #         return '母'
    #     else:
    #         return '輸入錯誤'


p1 = Animal(0, 18, 'yellow', 'bird')
# print(p1)
p1.print_type('燕子')  # 燕子的對象: 性別-母,年齡-18,顏色-yellow,類型-bird

4.寫一個圓類, 擁有屬性半徑、面積和周長;

要求獲取面積和周長的時候的時候可以根據(jù)半徑的值把對應(yīng)的值取到。

但是給面積和周長賦值的時候,程序直接崩潰,并且提示改屬性不能賦值

print()

class Circle:
    def __init__(self, radius):
        if isinstance(radius, int) or isinstance(radius, float):
            self._radius = radius
        else:
            raise ValueError
        self._area = math.pi * (radius**2)
        self._perimeter = math.pi * (radius*2)

    @property
    def radius(self):
        return self._radius

    @radius.setter
    def radius(self, value):
        if not (isinstance(value, int) or isinstance(value, float)):
            raise ValueError
        self._radius = value

    @property
    def area(self):
        self._area = math.pi * (self._radius ** 2)
        return self._area

    @area.setter
    def area(self, value):
        print("該屬性不能修改")
        raise ValueError

    @property
    def perimeter(self):
        self._perimeter = math.pi * (self._radius * 2)
        return self._perimeter

    @perimeter.setter
    def perimeter(self, value):
        print("該屬性不能修改")
        raise ValueError


p1 = Circle(5)
# print(p1.area)
p1.radius = 4
print(p1.area)

print()

5.寫一個撲克類, 要求擁有發(fā)牌和洗牌的功能(具體的屬性和其他功能自己根據(jù)實際情況發(fā)揮)

print()

class Pock:
    number = 54
    nums = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
    type_p = ['??', '??', '??', '??']
    pocker = []

    def __init__(self, kind, back_color):
        self.kind = kind
        self.back_color = back_color

    # 創(chuàng)建一副牌
    @staticmethod
    def establish():
        for type_i in Pock.type_p:
            for num in Pock.nums:
                Pock.pocker.append('%s%s' % (type_i, num))
        Pock.pocker.extend(["大王", "小王"])
        return Pock.pocker

    # 洗牌
    def cut_brand(self):
        random.shuffle(Pock.pocker)
        return Pock.pocker

    # 發(fā)牌
    def deal(self):
        poker_iter = iter(Pock.pocker)
        num = 1
        p_1 = []
        p_2 = []
        p_3 = []
        for _ in range(17*3):
            if num == 1:
                p_1.append(next(poker_iter))
            elif num == 2:
                p_2.append(next(poker_iter))
            elif num == 3:
                p_3.append(next(poker_iter))
                num = 0
            num += 1
        return p_1, p_2, p_3, list(poker_iter)


if __name__ == '__main__':

    p1 = Pock('1', 'yellow')
    print(p1.establish())  # 54
    print(p1.cut_brand())
    print(p1.deal())
from enum import Enum,unique
from random import shuffle


# 1.寫一個撲克類, 要求擁有發(fā)牌和洗牌的功能(具體的屬性和其他功能自己根據(jù)實際情況發(fā)揮)
@unique
class PokerNum(Enum):
    J = 11, 'J', 11
    Q = 12, 'Q', 12
    K = 13, 'K', 13
    A = 1, 'A', 14
    TWO = 2, '2', 15
    BigJoker = 15, '大王', 17
    SmallJoker = 14, '小王', 16


@unique
class PokerColor(Enum):
    Club = '?'
    Diamond = '?'
    Heart = '?'
    Spade = '?'
    Space = ''


class Poker:
    def __init__(self, num: PokerNum, color: PokerColor):
        self.num = num
        self.color = color

    def __repr__(self):
        if isinstance(self.num, PokerNum):
            return str(self.color.value) + str(self.num.value[1])
        return str(self.color.value)+str(self.num)

    def __gt__(self, other):
        if isinstance(self.num, PokerNum):
            a = self.num.value[2]
        else:
            a = self.num

        if isinstance(other.num, PokerNum):
            b = other.num.value[2]
        else:
            b = other.num

        return a > b


class Game:
    # 斗地主
    def __init__(self):
        pokers = []
        colors = [PokerColor.Club, PokerColor.Diamond, PokerColor.Heart, PokerColor.Spade]
        nums = [PokerNum.A, PokerNum.TWO, 3, 4, 5, 6, 7, 8, 9, 10, PokerNum.J, PokerNum.Q, PokerNum.K]
        for num in nums:
            for color in colors:
                p = Poker(num, color)
                pokers.append(p)
        pokers.extend([Poker(PokerNum.SmallJoker, PokerColor.Space), Poker(PokerNum.BigJoker, PokerColor.Space)])
        self.pokers = pokers
        self.pokers_iter = iter(self.pokers)

    # 洗牌
    def shuffling(self):
        shuffle(self.pokers)
        self.pokers_iter = iter(self.pokers)

    # 斗地主發(fā)牌方式
    def deal1(self):
        ps1 = []
        ps2 = []
        ps3 = []
        for _ in range(17):
            ps1.append(next(self.pokers_iter))
            ps2.append(next(self.pokers_iter))
            ps3.append(next(self.pokers_iter))
        ps1.sort(reverse=True)
        ps2.sort(reverse=True)
        ps3.sort(reverse=True)
        return ps1, ps2, ps3, list(self.pokers_iter)


game1 = Game()
game1.shuffling()
p1, p2, p3, di = game1.deal1()
print(p1)
print(p2)
print(p3)
print('底牌:', di)

print()

6.(嘗試)寫一個類,其功能是:

1.解析指定的歌詞文件的內(nèi)容

2.按時間顯示歌詞 提示:歌詞文件的內(nèi)容一般是按下面的格式進(jìn)行存儲的。

歌詞前面對應(yīng)的是時間,在對應(yīng)的時間點可以顯示對應(yīng)的歌詞

[00:00.20]藍(lán)蓮花

[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]當(dāng)你低頭地瞬間

[02:26.79][02:05.72][00:37.16]才發(fā)覺腳下的路

[02:32.17][00:42.69]心中那自由地世界

[02:37.20][00:47.58]如此的清澈高遠(yuǎn)

[02:42.32][00:52.72]盛開著永不凋零

[02:47.83][00:57.47]藍(lán)蓮花

class Lyric:
    def __init__(self, time, word):
        value = float(time[1:3])*60 + float(time[4:])
        self.time = value
        self.word = word

    def __repr__(self):
        return '<'+str(self.time) + ':' + self.word+'>'

    def __gt__(self, other):
        return self.time > other.time


class LyricAnalysis:

    def __init__(self, name):
        # 歌名
        self.name = name
        self.__all_lyrics = []

    def get_word(self, time):
        # =======解析歌詞文件======
        if not self.__all_lyrics:
            print('解析歌詞')
            with open('files/'+self.name) as f:
                while True:
                    line = f.readline()
                    if not line:
                        break
                    lines = line.split(']')
                    word = lines[-1]
                    for t in lines[:-1]:
                        lyric = Lyric(t, word)
                        self.__all_lyrics.append(lyric)

            # 排序
            self.__all_lyrics.sort(reverse=True)

        # ==========獲取歌詞==========
        for lyric in self.__all_lyrics:
            if lyric.time <= time:
                return lyric.word


ly = LyricAnalysis('藍(lán)蓮花')
print('===:', ly.get_word(123))
print('===:', ly.get_word(10))
print('===:', ly.get_word(89))
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 一,身體健康最重要。 因腰椎間盤突出老毛病作怪,且更加嚴(yán)重,最后起床疼痛得錐心,汗水直冒,在家屬攙扶下花兩三個小時...
    巴鄉(xiāng)渝民閱讀 404評論 0 2
  • 曾國藩告訴你:讀書,不是一回事 ...
    輕飏淺唱閱讀 544評論 1 3
  • 周末妻子白班,被感冒折騰了好了幾天的我早上送妻子和兒子去單位。老婆要在醫(yī)院監(jiān)督兒子的假期作業(yè),兒子也要求我送完娘兩...
    沈水之南閱讀 115評論 0 0
  • es6 的class類的繼承 運用es6 class繼承 通過繼承React.Component類來定義一個組件
    樊小勇閱讀 195評論 0 0
  • 與大多數(shù)家長一樣,孩子從小到大每個成長年齡段因各種問題沒少糾結(jié)過,也足以說明我們對孩子成長過程的重視和...
    小婉懿閱讀 283評論 0 3

友情鏈接更多精彩內(nèi)容