MagicforestA 2022-06-25 16:27 采纳率: 100%
浏览 44
已结题

python class和try-exception问题

提问在注释里


class StudentsDataException(Exception):
    pass

 #这里的pass是pass所有exception,下面代码为何还要raise exception?

class BadLine(StudentsDataException):
    def __init__(self, line_number, line_string):
        super().__init__(self)
        self.line_number = line_number
        self.line_string = line_string
这个class的具体作用是什么,能否解释一下每条代码的作用


class FileEmpty(StudentsDataException):
    def __init__(self):
        super().__init__(self)


from os import strerror


data = { }

file_name = input("Enter student's data filename: ")
line_number = 1
try:
    f = open(filename, "rt")
   
    lines = f.readlines()
    f.close()
    
    if len(lines) == 0:
        raise FileEmpty()
    
    for i in range(len(lines)):
        
        line = lines[i]
        
        columns = line.split()
       
        if len(columns) != 3:
            raise BadLine(i + 1, line)#能否解释一下(i+1,line)是什么情况
        
        student = columns[0] + ' ' + columns[1]
       
        try:
            points = float(columns[2])
        except ValueError:
            raise BadLine(i + 1, line)
        
        try:
            #print(data[student]),这里print根本没有显示任何内容,只是想看一下能print什么
            data[student] += points#想知道data[student]起始是不是0
        except KeyError:
            data[student] = points#keyerror的话没有映射对象,这里的“data[student] = points”代表什么意思
    
    for student in sorted(data.keys()):
        print(student,'\t', data[student])

except IOError as e:
    print("I/O error occurred: ", strerror(e.errno))
except BadLine as e:
    print("Bad line #" + str(e.line_number) + " in source file:" + e.line_string)
except FileEmpty:
    print("Source file empty")


"""
文件里的内容:
John    Smith    5
Anna    Boleyn    4.5
John    Smith    2
Anna    Boleyn    11
Andrew    Cox    1.5

最后的output是
Andrew Cox      1.5
Anna Boleyn      15.5
John Smith      7.0
"""

  • 写回答

2条回答 默认 最新

  • CSDN专家-sinJack 2022-06-25 16:41
    关注

    raise是抛出异常的意思

    
    except IOError as e:
        print("I/O error occurred: ", strerror(e.errno))
    except BadLine as e:
        print("Bad line #" + str(e.line_number) + " in source file:" + e.line_string)
    except FileEmpty:
        print("Source file empty")
    

    try except 才处理异常。

    #定义一个异常StudentsDataException子类,类中有两个属性,一个代码所在行,一个异常信息
    class BadLine(StudentsDataException):
        def __init__(self, line_number, line_string):
            super().__init__(self)
            self.line_number = line_number
            self.line_string = line_string
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 7月3日
  • 已采纳回答 6月25日
  • 创建了问题 6月25日

悬赏问题

  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来