美文网首页
2018-10-18day15类方法和静态方法

2018-10-18day15类方法和静态方法

作者: MW演员 | 来源:发表于2018-10-18 23:17 被阅读0次

    1.定义一个学生类。有属性:姓名、年龄、成绩(语文,数学,英语)[每课成绩的类型为整数]

    方法: a. 获取学生的姓名:getname() b. 获取学生的年龄:getage()
    c. 返回3门科目中最高的分数。get_course()

    class Student(object):
        """学生类"""
        def __init__(self, name, age):
            self.name = name
            self.age = age
            self._scores = []
    
        @property
        def score(self):
            return '语文:' + str(self.scores[0]) +  '数学:' + str(self.scores[1]) + \
            '英语:' + str(self.scores[2])
    
        @score.setter
        def score(self, scores):
            for score in scores:
                if isinstance(score, int):  # 判断分数是否是整型
                    self._scores.append(score)
                    continue
                else:
                    self._scores.clear()
                    raise ValueError
    
        def get_name(self):
            print(self.name)
    
        def get_age(self):
            print(self.age)
    
        def get_course(self):
            index = 0
            max1 = self._scores[0]
            for index in range(len(self._scores)):
                if self._scores[index] > max1:
                    max1 = self._scores[index]
                    obj = index
            if obj == 0:
                ke = '语文'
            elif obj == 1:
                ke = '数学'
            elif obj == 2:
                ke = '英语'
            print('最高分为:%s %d分' % (ke, max1))
    
    p1 = Student('小明', 18)
    # 获取姓名和年龄
    p1.get_name()
    p1.get_age()
    # 设置分数
    p1.score = 80, 90, 78
    # 获取所有信息
    print(p1.__dict__)
    # 获取最高分
    p1.get_course()
    

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

    class Person(object):
        """这是一个人类"""
        count = 0
    
        def __init__(self, name, age):
            self.name = name
            self.age = age
            Person.counts()
    
        @classmethod
        def counts(cls):
            cls.count += 1
    
    # 创建对象
    per1 = Person('zhangsan', 12)
    per2 = Person('lisi', 13)
    per3 = Person('wangwu', 18)
    # 获取已经创建的对象个数
    print(Person.count)
    

    赋值时要求age的值只能在0-150之间,超过范围报错;获取age的值的时候,返回年龄值,并且返回这个年龄对应的阶段

    class Person(object):
        """这是一个人类
        """
        def __init__(self, name:str):
            self.name = name
            self._age = 0
    
        @property
        def age(self):
            if 0 <= self._age <= 12:
                return (self._age, '儿童')
            elif 12 < self._age <= 18:
                return (self._age, '未成年')
            elif 18 < self._age <= 30:
                return (self._age, '成年人')
            elif 30 < self._age <= 50:
                return (self._age, '中年')
            else:
                return (self._age, '老年')
    
        @age.setter
        def age(self, value:int):
            if not isinstance(value, int):
                raise  ValueError
            if  not (0 <= value <= 150):
                raise ValueError
            self._age = value
    
    per1 = Person('小明')
    # per1.age = 180   # ValueError
    per1.age = 22
    print(per1.age)   # (22, '成年人')
    

    (尝试)5.写一个类,其功能是:

    • 1.解析指定的歌词文件的内容
    • 2.按时间显示歌词 提示:歌词文件的内容一般是按下面的格式进行存储的。
      歌词前面对应的是时间,在对应的时间点可以显示对应的歌词
    import module.file_manager as file_manager
    import re
    
    lyric_list = file_manager.text_read_file('lyric.txt')
    
    all_lyrics = {}
    
    class Lyric(object):
       """这是一个歌词类"""
       def __init__(self, music):
           self.music = music
    
       def get_lyric(self, time:int):
           if time in all_lyrics:
               print(all_lyrics[time])
           else:
               keys = sorted(all_lyrics.keys())
               for x in range(len(keys)):
                   if x+1 < len(keys) and keys[x] < time < keys[x+1]:
                       print(all_lyrics[keys[x]])
                       break
               else:
                   print('没有这么长的时间~~~')
                   return
    
       def  analysis(self):
           for lys in lyric_list:
               temp = ''
               times = re.findall(r'\d\d.\d\d.\d\d', lys)
               value = re.findall(r'[\u4e00-\u9fa5]', lys)
               # print(times,type(times),value,type(value))
               if len(times) == 1:
                   for str in value:
                       temp += str
                   all_lyrics[times[0]] = temp
               else:
                   for str in value:
                       temp += str
                   for tim in times:
                       all_lyrics[tim] = temp
               time = 0
           for tim in all_lyrics.copy():
               time = int(tim[:2]) * 60 + float(tim[3:])
               all_lyrics[int(time)] = all_lyrics[tim]
               del all_lyrics[tim]
    
    
    ly = Lyric('wei') # 创建对象
    ly.analysis()       # 解析歌词
    # keys = sorted(all_lyrics.keys())
    # print(keys)
    # print(all_lyrics)
    ly.get_lyric(163) # 获取歌词
    ly.get_lyric(162)
    
    

    相关文章

      网友评论

          本文标题:2018-10-18day15类方法和静态方法

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