![](/img/trans.png)
[英]How to access a class object inside a list when a value for one of the class attributes is given in Python?
[英]How to change one or more attributes of a Python class/object based on their value
我想创建一个 Python 类来存储学生的姓名和成绩,并检查成绩是否在正确的范围内(0-10)。
有没有办法将大于10的属性改为0(不是一一)?
class Student:
def __init__(self, name, lastName, programming, algebra,
calculus, physics, writing):
self.name = name
self.lastName = lastName
self.programming = programming
self.algebra = algebra
self.calculus = calculus
self.physics = physics
self.writing = writing
def check(self):
if self.programming or self.algebra or self.calculus or self.physics or self.writing not in range(11):
#Change the value of the attributes which are > 10 to 0
#Is there any way to do it apart from this one?
#if self.programming not in range(11):
#self.programming = 0
#if self.algebra not in range(11):
#self.algebra = 0
...................
您可以使用属性和 setter 并防止 setter 中的错误值:
class Student:
def __init__(self, name, programming ):
self.name = name
self.programming = programming # using the setter so our business rule is applied
@property
def programming(self):
return self._programming
@programming.setter
def programming(self,n):
# apply the businessrule of n being in 1 to 10 else 0
self._programming = n if 0 < n < 11 else 0
studs = [ Student("Enya",20), Student("Eric",0), Student("Karl",5)]
for s in studs:
print(s.name, s.programming)
输出:
Enya 0
Eric 0
Karl 5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.