我试图找到一种从self.average
类获取Basketball
变量的所有实例的列表的方法。然后,我将执行max(list)
以获取最大值。
class Basketball:
def __init__(self, name, goals, shots):
self.name = name
self.goals = goals
self.shots = shots
self.average = shots / goals
def display_average(self):
"""
>>> b1 = Basketball("Karen", 20, 80)
>>> b1.display_average()
'Player: Karen, average goals per game: 4'
"""
returnString = f"Player: {self.name}, average goals per game: {self.average:.2f}"
return returnString
if __name__ == "__main__":
player1 = Basketball("Karen", 20, 80)
print(player1.display_average())
player2 = Basketball("Alex", 4, 19)
print(player2.display_average())
最佳答案
您可以创建一个列表,并将该类的所有实例存储在其中。然后,您可以从列表中提取所有平均值并从中获取最大值。我将使用这样的列表理解:
if __name__ == "__main__":
basketball_list = []
basketball_list.append(Basketball("Karen", 20, 80))
basketball_list.append(Basketball("Alex", 4, 19))
best_avg = max([i.average for i in basketball_list])