python - 有没有办法在类的 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.
解决方案
是的,您可以在构造函数中很好地使用条件,但您不需要它们。您可以使用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
.
推荐阅读
- java - 对编写存储字符的 ListADT 感到困惑
- phpmyadmin - 如何加密phpmyadmin中的表
- apache-kafka - Kafka 主题级别的配置更改什么时候生效?
- go - Cannot defer close request body
- axon - Axon 框架:在命令处理程序期间仅应用第一个事件
- laravel - 我的 laravel recaptcha 不工作,如何整合?
- php - 无法在 PHP 5.5 上安装 libsodium
- typescript - 为什么 Typescript 会允许不正确的重载函数返回?
- oracle - 为什么视图列的类型与对应的函数结果类型不匹配?
- java - Java将8位字符串二进制表示转换为字节并再次返回