【问题标题】:Need help in implementing error handling in code stated below [duplicate]在下面所述的代码中实现错误处理时需要帮助[重复]
【发布时间】:2021-02-27 19:14:29
【问题描述】:

我编写了一个代码,用于收集学生的作业/考试结果并将其放入学生字典对象列表中。在代码中还有一个字典,其中包含每个作业或考试的权重。这让我可以计算加权结果。如何在此代码中实现错误处理,以便在权重字典包含与学生字典中存储的条目不匹配的条目时引发错误?

例如: 学生口语:A1、A2、A3 权重:A1、E1(由于 E1 不存在而引发错误)

[当前代码]

class Student:
# Part 1a: Creating student class
    def __init__(self, stud_dict):
        self.name = stud_dict['name']
        self.results = stud_dict['results'].copy()

# Part 2: Getting weighted result
    def get_weighted_result(self, weights):
        result = 0
        for key in weights:
            result += weights[key] * self.results[key]
        return result

# Part 1b: Converting student dictionary list to student object list
def dict_to_class_obj(stud_dicts):
    students = []
    for stud_dict in stud_dicts:
        students.append(Student(stud_dict))
    return students

#Test Section
stud_dicts = [
    {
        "name": "Fus Ro Dah",
        "results": {
            "assignment_1": 10,
            "assignment_2": 10,
            "examination_1": 10,
        }
    },
    {
        "name": "Foo Barry",
        "results": {
            "assignment_1": 1,
            "assignment_2": 2,
            "examination_1": 3,
        }
    },
]

# creating Student objects list
students = dict_to_class_obj(stud_dicts)
print(students[0].name)
print(students[0].results)
print(students[0].get_weighted_result({"assignment_1": 1.0, "examination_1": 9.0}))  

【问题讨论】:

  • def get_weighted_result(self, weights): if weights.keys() != self.results.keys(): raise Exception("Weights do not match results") ... 或者更精确的错误:def get_weighted_result(self, weights): for item in self.results: if item not in weights: raise Exception("'{}' missing in weights".format(item)) result = 0 ...

标签: python


【解决方案1】:

这个问题的一般答案是

if error_condition is True:
  raise Exception("Description of the problem")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-27
    • 1970-01-01
    • 2023-04-01
    相关资源
    最近更新 更多