2019-08-09/10_Work_Day15

1. 建立一个汽车类Auto,包括轮胎个数,汽车颜色,车身重量,速度等属性,并通过不同的构造方法创建实例。至少要求 汽车能够加速 减速 停车。 再定义一个小汽车类CarAuto 继承Auto 并添加空调、CD属性,并且重新实现方法覆盖加速、减速的方法
class CorrectType(Exception):
    """类型错误异常"""

    def __str__(self):
        return 'Wrong type!'


class WriteError(Exception):
    """只读异常"""

    def __str__(self):
        return 'Modify read-only properties!'


class Auto:
    """汽车类"""

    def __init__(self, tires_num, color, weight, speed=0):
        """
        :param tires_num: 轮胎个数
        :param color: 汽车颜色
        :param weight: 车身重量
        :param speed: 起始速度
        """
        self._tires_num = self.tires_num = tires_num
        self._color = color
        self.weight = weight
        if not (isinstance(speed, int) or isinstance(speed, float)) or speed < 0:
            raise CorrectType
        else:
            self._speed = speed

    @property
    def tires_num(self):
        return self._tires_num

    @tires_num.setter
    def tires_num(self, value):
        if not isinstance(value, int) or value <= 0:
            raise CorrectType
        self._tires_num = value

    @property
    def color(self):
        return self._tires_num

    @color.setter
    def color(self, value):
        if not isinstance(value, str):
            raise CorrectType
        self._tires_num = value

    @property
    def weight(self):
        return self._tires_num

    @weight.setter
    def weight(self, value):
        if not Auto.is_num(value):
            raise CorrectType
        self._tires_num = value

    @property
    def speed(self):
        return self._speed

    @speed.setter
    def speed(self, value):
        """速度只能通过加速/减速/停车方法改变"""
        raise WriteError

    def accelerate(self, sp):
        """加速"""
        if not Auto.is_num(sp):
            raise CorrectType
        old_speed = self.speed
        self._speed += sp
        print('The auto is accelerating({} -> {}), the current speed is {} km/h.'
              .format(old_speed, self.speed, self.speed))

    def decelerate(self, sp):
        """减速"""
        if not Auto.is_num(sp):
            raise CorrectType
        old_speed = self.speed
        self._speed = self._speed - sp if self._speed >= sp else 0
        print('The auto is decelerating({} -> {}), the current speed is {} km/h.'
              .format(old_speed, self.speed, self.speed))

    def stop(self):
        self._speed = 0
        print('The auto stopped, the current speed is {} km/h'.format(self.speed))

    @staticmethod
    def is_num(value):
        """是否是正数"""
        return isinstance(value, int) or isinstance(value, float) or value > 0

    def __repr__(self):
        return ''.join(['<', str(self.__dict__)[1:-1], '>'])


class CarAuto(Auto):
    """小汽车类"""

    def __init__(self, tires_num, color, weight, speed=0, air_conditioning=False, cd=False):
        """
        :param tires_num: 轮胎个数
        :param color: 汽车颜色
        :param weight: 车身重量
        :param speed: 起始速度
        :param air_conditioning: 是否有空调
        :param cd: 是否有CD
        """
        super().__init__(tires_num, color, weight, speed)
        self.air_conditioning = air_conditioning
        self.cd = cd

    def accelerate(self, sp):
        old_speed = self.speed
        self._speed += sp
        print('The car is accelerating({} -> {}), the current speed is {} km/h.'
              .format(old_speed, self.speed, self.speed))

    def decelerate(self, sp):
        """减速"""
        old_speed = self.speed
        self._speed = self._speed - sp if self._speed >= sp else 0
        print('The car is decelerating({} -> {}), the current speed is {} km/h.'
              .format(old_speed, self.speed, self.speed))
auto1 = Auto(4, 'black', 300)

auto1.accelerate(20)
# The auto is accelerating(0 -> 20), the current speed is 20 km/h.
auto1.decelerate(10)
# The auto is decelerating(20 -> 10), the current speed is 10 km/h.
auto1.stop()
# The auto stopped, the current speed is 0 km/h

car1 = CarAuto(4, 'red', 200, air_conditioning=True)
car1.accelerate(40)
# The car is accelerating(0 -> 40), the current speed is 40 km/h.
car1.decelerate(20)
# 1The car is decelerating(40 -> 20), the current speed is 20 km/h.
2. 创建一个Person类,添加一个类字段用来统计Person类的对象的个数
class Person:
   count = 0

   def __init__(self, name, age, gender):
      self.name = name
      self.age = age
      self.gender = gender
      Person.count += 1

   def __repr__(self):
      return ''.join(['<', str(self.__dict__)[1:-1], '>'])
p1 = Person('Lina', 19, 'female')
print(Person.count)  # 1
p2 = Person('Jack', 18, 'male')
print(Person.count)  # 1
p3 = Person('Kin', 20, 'male')
print(Person.count)  # 1
3. 创建一个动物类,拥有属性:性别、年龄、颜色、类型 ,
要求打印这个类的对象的时候以'/XXX的对象: 性别-? 年龄-? 颜色-? 类型-?/' 的形式来打印
class Animal:
   def __init__(self, gender, age, color, species):
      self.gender = gender
      self.age = age
      self.color = color
      self.species = species

   def __repr__(self):
      """/XXX的对象: 性别-? 年龄-? 颜色-? 类型-?/'"""
      return '/{}的对象: 性别-{} 年龄-{} 颜色-{} 类型-{}/' \
         .format(self.__class__.__name__, self.gender, self.age, self.color, self.species)


class Cat(Animal):
   pass


class Dog(Animal):
   pass
a1 = Animal('公', 3, '白色', '哺乳动物')
print(a1)  # /Animal的对象: 性别-公 年龄-3 颜色-白色 类型-哺乳动物/
c1 = Cat('母', 2, '灰白相间', '布偶猫')
print(c1)  # /Cat的对象: 性别-母 年龄-2 颜色-灰白相间 类型-布偶猫/
d1 = Dog('公', 1, '黑', '哈士奇')
print(d1)  # /Dog的对象: 性别-公 年龄-1 颜色-黑 类型-哈士奇/
4. 写一个圆类, 拥有属性半径、面积和周长;要求获取面积和周长的时候的时候可以根据半径的值把对应的值取到。但是给面积和周长赋值的时候,程序直接崩溃,并且提示改属性不能赋值
class Circle:
   pi = 3.141592653589793

   def __init__(self, radius):
      self.radius = radius
      self._area = Circle.pi * self.radius ** 2
      self._perimeter = 2 * Circle.pi * self.radius

   @property
   def area(self):
      self._area = Circle.pi * self.radius ** 2
      return self._area

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

   @property
   def perimeter(self):
      self._perimeter = 2 * Circle.pi * self.radius
      return self._perimeter

   @perimeter.setter
   def perimeter(self, value):
      raise WriteError

    def __repr__(self):
        return '<radius: {}, area: {}, perimeter: {}>'\
            .format(self.radius, self.area, self.perimeter)
c1 = Circle(10)
print(c1)  # <radius: 10, area: 314.1592653589793, perimeter: 62.83185307179586>
c1.area = 100  # __main__.WriteError: Modify read-only properties!
c1.perimeter = 30  # __main__.WriteError: Modify read-only properties!
c1.radius = 5
print(c1)  # <radius: 5, area: 78.53981633974483, perimeter: 31.41592653589793>
5. 写一个扑克类, 要求拥有发牌和洗牌的功能(具体的属性和其他功能自己根据实际情况发挥)
from random import shuffle


class CorrectType(Exception):
    """类型错误异常"""

    def __str__(self):
        return 'Wrong type!'


class Poker:
    __colors = ['♥️', '♠️', '♦️', '♣️']
    __nums = ['3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A', '2']

    def __init__(self):
        self.__cards = [i for i in range(54)]
        shuffle(self.__cards)

        self.__top_cards = self.__cards[:3]

        # 对分组的牌排序
        self.__p1 = self.__p2 = self.__p3 = []
        self.__p1 = Poker.__sorted_cards(self.__cards[3:20])
        self.__p2 = Poker.__sorted_cards(self.__cards[20:37])
        self.__p3 = Poker.__sorted_cards(self.__cards[37:])

    @property
    def cards(self):
        return Poker.__set_cards(self.__cards)

    @cards.setter
    def cards(self, value):
        # self.__cards = [i for i in range(54)]
        # shuffle(self.__cards)
        raise WriteError

    @property
    def top_cards(self):
        return Poker.__set_cards(self.__top_cards)

    @top_cards.setter
    def top_cards(self, value):
        raise WriteError

    @property
    def p1(self):
        return Poker.__set_cards(self.__p1)

    @p1.setter
    def p1(self, value):
        raise WriteError

    @property
    def p2(self):
        return Poker.__set_cards(self.__p2)

    @p2.setter
    def p2(self, value):
        raise WriteError

    @property
    def p3(self):
        return Poker.__set_cards(self.__p3)

    @p3.setter
    def p3(self, value):
        raise WriteError

    @staticmethod
    def __sorted_cards(cards: list):
        """数组排序"""
        self_cards = sorted(cards)
        return self_cards

    def to_be_landlord(self):
        """叫地主阶段,共两轮,如果没有玩家叫地主,流局重新洗牌"""
        times = 2
        while times:
            for i in range(1, 4):
                player = ''.join(['p', str(i)])
                choice = str(i) + input('{}是否叫地主(y/n):'.format(player))
                if choice[-1] == 'y':
                    # 拼接属性名
                    player = '_Poker__' + player
                    # print(player)
                    # 动态获取当前叫地主的玩家(p1-p3)
                    p = getattr(self, player)
                    # 将顶牌加入后,该玩家手牌重写排序
                    setattr(self, player, Poker.__sorted_cards(p + self.__top_cards))
                    self.__top_cards.clear()
                    print('\n叫地主完成,地主为{}'.format(player[-2:]))
                    print(self)
                    return
                else:
                    continue
            times -= 1
        print('无人叫地主,本局流局...\n重新发牌:')
        self.__init__()
        print(self)
        self.to_be_landlord()

    @classmethod
    def __set_cards(cls, part_cards: list):
        """返回有花色和大小的展示牌组"""
        part_len = len(part_cards)
        out_cards = ['' for _ in range(part_len)]
        for index in range(part_len):
            if part_cards[index] == 52:
                out_cards[index] = 'Black Joker'
            elif part_cards[index] == 53:
                out_cards[index] = 'Red Joker'
            else:
                # 按大小排
                out_cards[index] = cls.__colors[part_cards[index] % 4] + cls.__nums[part_cards[index] // 4]
        return out_cards

    def __repr__(self):
        # return 'top_cards: {}\np1: {}\np2: {}\np3: {}' \
        #   .format(self.__top_cards, self.__p1, self.__p2, self.__p3)
        return 'top_cards: {}\np1: {}\np2: {}\np3: {}' \
            .format(self.top_cards, self.p1, self.p2, self.p3) if self.__top_cards else \
            'p1: {}\np2: {}\np3: {}'.format(self.p1, self.p2, self.p3)
    poker = Poker()
    print(poker)
    poker.to_be_landlord()
    '''
    top_cards: ['♠️J', '♦️5', '♠️7']
    p1: ['♥️4', '♣️4', '♠️5', '♣️5', '♥️6', '♥️7', '♦️7', '♠️8', '♣️8', '♥️10', '♦️J', '♥️Q', '♠️Q', '♥️K', '♠️K', '♦️K', '♠️2']
    p2: ['♠️3', '♦️3', '♣️3', '♠️4', '♦️6', '♣️7', '♦️8', '♠️9', '♦️10', '♥️J', '♥️A', '♠️A', '♣️A', '♥️2', '♣️2', 'Black Joker', 'Red Joker']
    p3: ['♥️3', '♦️4', '♥️5', '♠️6', '♣️6', '♥️8', '♥️9', '♦️9', '♣️9', '♠️10', '♣️10', '♣️J', '♦️Q', '♣️Q', '♣️K', '♦️A', '♦️2']
    p1是否叫地主(y/n):
    p2是否叫地主(y/n):
    p3是否叫地主(y/n):
    p1是否叫地主(y/n):y
    
    叫地主完成,地主为p1
    p1: ['♥️4', '♣️4', '♠️5', '♦️5', '♣️5', '♥️6', '♥️7', '♠️7', '♦️7', '♠️8', '♣️8', '♥️10', '♠️J', '♦️J', '♥️Q', '♠️Q', '♥️K', '♠️K', '♦️K', '♠️2']
    p2: ['♠️3', '♦️3', '♣️3', '♠️4', '♦️6', '♣️7', '♦️8', '♠️9', '♦️10', '♥️J', '♥️A', '♠️A', '♣️A', '♥️2', '♣️2', 'Black Joker', 'Red Joker']
    p3: ['♥️3', '♦️4', '♥️5', '♠️6', '♣️6', '♥️8', '♥️9', '♦️9', '♣️9', '♠️10', '♣️10', '♣️J', '♦️Q', '♣️Q', '♣️K', '♦️A', '♦️2']
    '''
6. (尝试)写一个类,其功能是:1.解析指定的歌词文件的内容 2.按时间显示歌词 提示:歌词文件的内容一般是按下面的格式进行存储的。歌词前面对应的是时间,在对应的时间点可以显示对应的歌词
[00:00.20]蓝莲花   
[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]当你低头地瞬间  
[02:26.79][02:05.72][00:37.16]才发觉脚下的路   
[02:32.17][00:42.69]心中那自由地世界  
[02:37.20][00:47.58]如此的清澈高远   
[02:42.32][00:52.72]盛开着永不凋零   
[02:47.83][00:57.47]蓝莲花  
import time
import re


class CorrectType(Exception):
    """类型错误异常"""

    def __str__(self):
        return 'Wrong type!'


class LyricsAnalysis:
    """解析歌词文件及显示歌词"""
    def __init__(self):
        self.__lyric_list = []

    @property
    def lyric_list(self):
        return self.__lyric_list

    @lyric_list.setter
    def lyric_list(self, value):
        raise WriteError

    def analysis(self, path: str):
        """分析歌词文件"""
        with open(path, 'r', encoding='utf-8') as f:
            line = f.readline()
            while line:
                r1 = re.compile(r'(\d{2}:\d{2}\.\d{2})')  # r1分离时间
                # r'([\u4E00-\u9FA5A-Za-z:./-]*)(?:\n)$'
                r2 = re.compile(r'(?:])(\D+)$')  # r2分离歌词,匹配']'(不显示)和非数字类型
                ti = r1.findall(line)
                ly = r2.findall(line)
                # print(ti, ly)
                if ti:
                    for key in r1.findall(line):
                        key = LyricsAnalysis.__to_second(key)
                        value = ly[0] if ly else ''
                        # print(key, value)
                        self.__lyric_list.append([key, value])
                self.__lyric_list.sort()
                line = f.readline()

    def show_lyrics(self, speed=0):
        """显示歌词"""
        for index in range(len(self.__lyric_list) - 1):
            last_time = self.__lyric_list[index][0]
            this_time = self.__lyric_list[index + 1][0]
            sleep_time = this_time - last_time
            if sleep_time > 2:
                if not index % 10:
                    speed = sleep_time / 15 + sleep_time / 100
                else:
                    speed = sleep_time / 15
            else:
                if not index % 5:
                    speed = sleep_time / 45 + sleep_time / 20
                else:
                    speed = sleep_time / 45
            while sleep_time > speed:
                # print(this_time - last_time)
                print('\r{}\t\t{:.2f}'.format(self.__lyric_list[index][1][:-1], sleep_time), end='')
                time.sleep(speed)
                sleep_time -= speed
        print('\r{}'.format(self.__lyric_list[-1][1]))

    @staticmethod
    def __to_second(str1: str):
        """字符串时间转换秒"""
        r = re.compile(r'(?::)')  # 分离分钟和秒
        result = r.split(str1)
        minute = result[0]
        return int(minute) * 60 + float(result[1])
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,530评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 86,403评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,120评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,770评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,758评论 5 367
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,649评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,021评论 3 398
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,675评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,931评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,659评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,751评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,410评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,004评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,969评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,203评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,042评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,493评论 2 343