如何将值附加到类中的参数列表? [复制]
python 434
原文标题 :How can I append values to a parameter list in a class? [duplicate]
这个问题在这里已经有了答案:”Least Astonishment” and the Mutable Default Argument (32 answers) Closed 2 hours ago 。
积分对象最初是一个空列表,当球队参加不同的运动时,他们的积分会被添加到列表中。然后将分数相加并取平均值,如果平均值 >= 60,则团队排名第三。如果平均值 >= 80,则团队排名第二。如果平均值 >= 90,则团队排名第一。积分列表也应该按升序排列。
class Sports:
def __init__(self, team_name, team_colour, points = []):
self.team_name, self.team_colour, self.points = team_name, team_colour, points
def __str__(self):
average = 0
try:
average = sum(self.points)/len(self.points)
average = average
except ZeroDivisionError:
average = 0
if len(self.points) == 0:
return self.team_name + " " + str(sorted(self.points)) + " (No participation.)"
if average >= 60:
return self.team_name + " " + str(sorted(self.points)) + " (Third)"
if average >= 80:
return self.team_name + " " + str(sorted(self.points)) + " (Second)"
if average >= 90:
return self.team_name + " " + str(sorted(self.points)) + " (First)"
else:
return self.team_name + " " + str(sorted(self.points)) + " (You didn't place. Thanks for participating!)"
def add_points(self, point):
if point >= 0 and point <= 100:
self.points.append(point)
team1 = Sports('Dragons', 'Red')
team2 = Sports('Tigers', 'White')
team3 = Sports('Bulldogs', 'Blue')
team1.add_points(35)
team1.add_points(50)
team1.add_points(10)
team1.add_points(50)
team2.add_points(55)
team2.add_points(75)
team2.add_points(95)
team2.add_points(95)
team3.add_points(89)
team3.add_points(95)
team3.add_points(80)
team3.add_points(98)
print(team1)
print(team2)
print(team3)
我尝试通过以下方式将其附加到点列表中:
def add_points(self, point):
if point >= 0 and point <= 100:
self.points.append(point)
预期的输出应该是:
Dragons [10, 35, 50, 50] (You didn't place. Thanks for participating!)
Tigers [55, 75, 95, 95] (Second)
Bulldogs [80, 89, 95, 98] (Fist)
我得到的输出:
Dragons [10, 35, 50, 50, 55, 75, 80, 89, 95, 95, 95, 98] (Third)
Tigers [10, 35, 50, 50, 55, 75, 80, 89, 95, 95, 95, 98] (Third)
Bulldogs [10, 35, 50, 50, 55, 75, 80, 89, 95, 95, 95, 98] (Third)