美文网首页
day14 - 类和对象(作业)

day14 - 类和对象(作业)

作者: 未醒的梦_19b0 | 来源:发表于2018-11-22 21:34 被阅读0次

    0.定义一个学生类。有属性:姓名、年龄、成绩(语文,数学,英语)[每课成绩的类型为整数]方法: a. 获取学生的姓名:getname() b. 获取学生的年龄:getage()c. 返回3门科目中最高的分数。get_course()
    讲解:用一个字典类存成绩

    class Grade(object):
        def __init__(self, chinese:int, math, english):
            self.chinese = chinese
            self.math = math
            self.english = english
    
        def get_best_grade(self):
            all_score = list(self.__dict__.values())
            return max(all_score)
    
    
    class Students(object):
        def __init__(self, name, age, grade=Grade(0, 0, 0)):
            self.name = name
            self.age = age
            self.grade = grade
    
        def getname(self):
            return self.name
    
        def getage(self):
            return self.age
    
        def get_course(self):
            return self.grade.get_best_grade()
    
    
    stu1 = Students('小明', 18, Grade(chinese=80, math=90, english=95))
    print(stu1.get_course())
    
    class Student(object):
        def __init__(self, name, age, score):
            self.name = name
            self.age = age
            self.score = score
    
        def getname(self):
            return self.name
    
        def getage(self):
            return self.age
    
        def get_course(self):
            return max(self.score)
    
    
    stu1 = Student('tom', 18, [90, 95, 98])
    print(stu1.getname())
    print(stu1.getage())
    print(stu1.get_course())
    

    1.建立一个汽车类Auto,包括轮胎个数,汽车颜色,车身重量,速度等成员变量,并通过不同的构造方法创建实例。至少要求 汽车能够加速 减速 停车。 再定义一个小汽车类CarAuto 继承Auto 并添加空调、CD等成员变量 覆盖加速 减速的方法

    class Auto(object):
    
        def __init__(self, color='白色', weight=0):
            self.tyre = 4
            self.color = color
            self.weight = weight
            self.speed = 0
    
        def add_speed(self, speed: int):
            if self.speed + speed >= 240:
                print('您已超速!')
                self.speed = 240
                return
            self.speed += speed
    
        def sub_speed(self, speed: int):
            if self.speed - speed < 0:
                self.speed = 0
                return
            self.speed -= speed
    
        def stop(self):
            self.speed = 0
    
    
    class CarAuto(Auto):
        def __init__(self, color='', weight=0, air_conditioning='', cd=''):
            super().__init__(color, weight)
            self.air_conditioning = air_conditioning
            self.cd = cd
    
        def add_speed(self, speed: int):
            if self.speed + speed >= 260:
                print('您已超速!')
                self.speed = 240
                return
            self.speed += speed
    
        def sub_speed(self, speed: int):
            if self.speed - speed < 0:
                print('已经熄火!')
                self.speed = 0
                return
            self.speed -= speed
    
    class Auto(object):
        def __init__(self, count, color, weight, speed):
            self.count = count
            self.color = color
            self.weight = weight
            self.speed = speed
    
        def add_speed(self):
            return self.speed + 1
    
        def delete_speed(self):
            return self.speed - 1
    
        def stop_car(self):
            return self.speed == 0
    
    
    a1 = Auto(5, '白色', '3t', 200)
    # 再定义一个小汽车类CarAuto 继承Auto 并添加空调、CD等成员变量 覆盖加速 减速的方法
    class CarAuto(Auto):
        def __init__(self, *args, air, cd):
            super().__init__(*args)
            self.air = air
            self.cd = cd
    
        def add_speed(self):
            self.speed += 2
            return self.speed
    
        def delete_speed(self):
            self.speed -= 2
            return self.speed
    
    
    c1 = CarAuto(3, '白色', '2t', 200, air='格力', cd='VCD')
    print(c1.count)
    print(c1.speed)
    print(c1.add_speed())
    print(a1.add_speed())
    print(a1.add_speed())
    print(a1.delete_speed())
    print(c1.color)
    print(c1.delete_speed())
    

    2.创建一个名为User 的类,其中包含属性firstname 和lastname ,还有用户简介通常会存储的其他几个属性。在类User 中定义一个名 为describeuser() 的方法,它打印用户信息摘要;再定义一个名为greetuser() 的方法,它向用户发出个性化的问候。

    管理员是一种特殊的用户。编写一个名为Admin 的类,让它继承User类。添加一个名为privileges 的属性,用于存储一个由字符串(如"can add post"、"can delete post"、"can ban user"等)组成的列表。编写一个名为show_privileges()的方法,它显示管理员的权限。创建一个Admin 实例,并调用这个方法。

    class User(object):
    
        def __init__(self, firstname, lastname):
            self.firstname = firstname
            self.lastname = lastname
    
        def describeuser(self):
            print('%s:用户信息摘要'%(self.firstname + self.lastname))
    
        def greatuser(self):
            print('%s,你好!' % (self.firstname + self.lastname))
    #
    # 管理员是一种特殊的用户。编写一个名为Admin 的类,让它继承User类。添加一个名为privileges 的属性,
    # 用于存储一个由字符串(如"can add post"、"can delete post"、"can ban user"等)组成的列表。
    # 编写一个名为show_privileges()的方法,它显示管理员的权限。创建一个Admin 实例,并调用这个方法
    class Admin(User):
        def __init__(self, firstname, lastname, privieges):
            super().__init__(firstname, lastname)
            self.privileges = privieges
    
        def show_privileges(self):
            return self.privileges
    
    
    admin1 = User('zhang','san')
    admin2 = Admin('li', 'si', ['can add post', 'can delete post', 'can ban user'])
    admin1.describeuser()
    admin1.greatuser()
    print(admin2.show_privileges())
    

    3.创建一个Person类,添加一个类字段用来统计Perosn类的对象的个数

    class Person(object):
        count = 0
    
        def __init__(self):
            Person.count += 1
            
    
    p1 = Person()
    p1 = Person()
    p3 = Person()
    p4 = Person()
    p5 = Person()
    p6 = Person()
    p7 = Person()
    p8 = Person()
    print(Person.count)
    

    (尝试)5.写一个类,其功能是:1.解析指定的歌词文件的内容 2.按时间显示歌词 提示:歌词文件的内容一般是按下面的格式进行存储的。歌词前面对应的是时间,在对应的时间点可以显示对应的歌词

    [00:00.20]蓝莲花 [00:00.80]没有什么能够阻挡 [00:06.53]你对自由地向往 [00:11.59]天马行空的生涯 [00:16.53]你的心了无牵挂 02:11.27[00:21.95]穿过幽暗地岁月 02:16.51[00:26.83]也曾感到彷徨 02:21.81[00:32.30]当你低头地瞬间 02:26.79[00:37.16]才发觉脚下的路 02:32.17心中那自由地世界 02:37.20如此的清澈高远 02:42.32盛开着永不凋零 02:47.83蓝莲花

    def get_lyrics(time, song_name):
        pass
    
    class Lyrics(object):
        """歌词类"""
        def __init__(self, time: float, text: str):
            self.time = time
            self.text = text.replace('\n', '')
    
        def __gt__(self, other):
            return self.time > other.time
    
        def __repr__(self):
            return '%.2f:%s' % (self.time, self.text)
    
    
    class LyricsAnalyzer(object):
        """歌词解析类"""
        def __init__(self, song):
            self.__song = song
            self.__all_lyrics = []
    
        def __analysis_line(self, line):
            # 在这儿处理文件中的每一行的内容
            lines = line.split(']')
            # 创建歌词对象
            text = lines[-1]
            for time_str in lines[:-1]:
                fen = float(time_str[1:3])
                miao = float(time_str[4:])
                time = fen * 60 + miao
                lyrics = Lyrics(time, text)
                self.__all_lyrics.append(lyrics)
    
        def __annlysis_file(self):
            """解析歌词文件"""
            try:
                with open('lyricsfiles/%s.txt' % (self.__song), 'r',encoding='utf-8') as f:
                    line = f.readline()
                    while line:
                        self.__analysis_line(line)
                        line = f.readline()
            except FileNotFoundError:
                pass
                # print('没有歌词!')
    
        def get_lyrics(self, time):
            """
            根据当前时间获取对应歌词
            :param time: 时间(s)
            :return: 歌词
            """
            if not self.__all_lyrics:
                # 1.解析歌词文件
                self.__annlysis_file()
                # 2.根据时间对歌词进行排序
                self.__all_lyrics.sort(reverse=True)
                if not self.__all_lyrics:
                    return '[没有歌词!]'
                # print(self.__all_lyrics)
                # 3.根据时间找词
            for lyrics in self.__all_lyrics:
                if lyrics.time <= time:
                    return lyrics.text
    
    
    la1 = LyricsAnalyzer('蓝莲花')
    print(la1.get_lyrics(10))
    print(la1.get_lyrics(100))
    print(la1.get_lyrics(132))
    print(la1.get_lyrics(140))
    la2 = LyricsAnalyzer('夜曲')
    print(la2.get_lyrics(40))
    
    class ShowSong(object):
        def __init__(self):
            self._ms = 0
    
        def show_song(self):
            ms1 = float(input('时间:'))
            with open('1.txt', encoding='utf-8')as f:
                line1 = f.read()
                line2 = line1.split('\n')
                for i in range(len(line2) - 1):
                    line3 = line2[i][1:].split(']')
                    line5 = line2[i + 1][1:].split(']')
                    # print(line3[0], line3[1])
                    line4 = line3[0].split(':')
                    line6 = line5[0].split(':')
                    ms = float(line4[0]) * 60 + float(line4[1])
                    ms2 = float(line6[0]) * 60 + float(line6[1])
                    if ms <= ms1 < ms2:
                        print(line3[1])
                else:
                    print('蓝莲花')
    
    
    
    show1 = ShowSong()
    show1.show_song()
    

    相关文章

      网友评论

          本文标题:day14 - 类和对象(作业)

          本文链接:https://www.haomeiwen.com/subject/lmxrqqtx.html