如何在Python类的__init__方法中使用elif实现输入分数范围过滤?
解决方法
我们可以封装一个使用if-elif-else逻辑的分数校准函数,对三个科目分数分别做范围校验后再赋值给类属性即可,同时注意原有print_scores方法中字符串拼接多了一处空格,需要调整才能匹配预期输出。
完整修改后的代码
class student_scores(object): def __init__(self, name, id, math_score, english_score, science_score): self.name = name self.id = id self.math_score = math_score self.english_score = english_score self.science_score = science_score # 纯if-elif-else实现的分数校准逻辑 def adjust_score(score): if score > 90: return 90 elif score < 0: return 0 else: return score # 重新赋值校准后的分数到类属性 self.math_score = adjust_score(self.math_score) self.english_score = adjust_score(self.english_score) self.science_score = adjust_score(self.science_score) def print_scores(self): # 去掉了%s后面多余的空格,匹配预期输出格式 print("%s's math, english, science score is %d, %d, %d respectively."%(self.name, self.math_score, self.english_score, self.science_score)) student1 = student_scores("Kay", 20141, 50, 110, -10) student2 = student_scores("Lisa", 20304, 55, 70, 65) student3 = student_scores("Rin", 29850, 100, 11, 4) # 调用打印方法输出结果 student1.print_scores() student2.print_scores() student3.print_scores()
运行输出
Kay's math, english, science score is 50, 90, 0 respectively. Lisa's math, english, science score is 55, 70, 65 respectively. Rin's math, english, science score is 90, 11, 4 respectively.
和给出的预期结果完全一致。
内容的提问来源于stack exchange,提问作者J.Moon
相关产品推荐
相关产品推荐

