如何将值附加到类中的参数列表? [复制]

扎眼的阳光 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)

原文链接:https://stackoverflow.com//questions/71685745/how-can-i-append-values-to-a-parameter-list-in-a-class

回复

我来回复
  • aaossa的头像
    aaossa 评论

    这个问题很好地涵盖了这个问题。您的代码中的特殊问题是您在Sport类中使用列表作为默认参数。因为列表是可变对象,所以在每个函数调用中总是使用相同的列表。改为这样做:

    def __init__(self, team_name, team_colour, points=None):
        if points is None:
            points = list()
    

    您还可以使用单行版本:

    points = points if points else list()
    
    2年前 0条评论