首页 > 解决方案 > 有没有办法在类的 init() 函数中设置一个 elif 语句?

问题描述

我有目标使用 if-elif-else 函数来过滤输入的代码。

所以目标是制作一个过滤代码,过滤三个整数输入以得到一个从 0 到 90 的值。超过 90 的数字应该被赋值为 90,负数应该被赋值为 0。然而,输入被链接到母类'自己'。

所以我选择了 if-elif-else,因为它是最可取的选择,但我找不到正确的方法。

代码是

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
        # We need some codes here to match the conditions.
    def print_scores(self):
        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)
 

结果应打印为

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.

标签: pythonclassif-statement

解决方案


是的,您可以在构造函数中很好地使用条件,但您不需要它们。您可以使用min/max函数来限制值,例如

    self.math_score = min(max(0, math_score), 90)
    self.english_score = min(max(0, english_score), 90)
    self.science_score = min(max(0, science_score), 90)

如果输入为负,则max(0, value)返回0。如果输入高于 90,则min(value, 90)返回90.


推荐阅读