python-3.x - 向类添加方法以比较 Python 中的对象,但我的代码中不断出现错误
问题描述
这是我的任务:向比较两个 Student 对象的 Student 类添加方法。一种方法应该测试是否相等。其他方法应该支持其他可能的比较。在每种情况下,该方法都会返回两个学生姓名的比较结果。但由于某种原因,我不断收到错误消息。我不确定我做错了什么。
class Student(object):
def __init__(self, name, number):
self.name = name
self.scores = []
for count in range(number):
self.scores.append(0)
def getName(self):
return self.name
# method to set the score
def setScore(self, i, score):
self.scores[i - 1] = score
# method to get the score
def getScore(self, i):
return self.scores[i - 1]
# method to get the average
def getAverage(self):
return sum(self.scores) / len(self._scores)
# method to get the high score
def getHighScore(self):
return max(self.scores)
# method to print the object in string format
def __str__(self):
return "Name: " + self.name + "\nScores: " + \
" ".join(map(str, self.scores))
# checking for equality for the names
def __eq__(self,other):
if self.name == other.name:
return "Equal"
else:
return "Not Equal"
# checking for less than in names
def __lt__(self,other):
if self.name < other.name:
return "Less than"
else:
return "Not less than"
# checking for greater than or equal to names
def __ge__(self,other):
if self.name >other.name:
return "Greater than"
elif self.name == other.name:
return "Both are equal"
else:
return "Not greater or equal"
# main function
def main():
# creating student object
student = Student("Sofia", 5)
print(student)
for i in range(1, 6):
student.setScore(i, 100)
print(student)
# creating student2 object
student2= Student("Dom",5)
print(student2)
for i in range(1, 6):
student2.setScore(i, 100)
print(student2)
# checking the equality methods
print(student==student2)
print(student<student2)
print(student2<student)
print(student>=student2)
# calling the main function
if __name__ == "__main__":
main()
解决方案
推荐阅读
- android - 如何使用 navGraphHost 在片段中创建不同的操作栏。安卓
- javascript - WebdriverIO - 选择器中的 OR 逻辑运算符
- python - 无法在 PyTube 中显示进度条
- python - 使用 django 自定义过滤器进行迭代
- python - 如何从 python 套接字中读取整数?
- vue.js - Vue.js:路由发生变化,但其相应的组件未呈现。控制台中没有错误
- postgresql - 带有可选单词的 websearch_to_tsquery
- javascript - 如何在 React 中为动态渲染的组件设置状态变量
- html - mdbootstrap 表单标签与值重叠
- javascript - 如何将 Navbar(logo, View('Home', ... 从 Flask-Nav 模块的徽标转换为可点击的链接