gpt4 book ai didi

python - 如何从类中获取变量的每个实例的列表?

转载 作者:行者123 更新时间:2023-12-01 01:14:13 25 4
gpt4 key购买 nike

我正在尝试找到一种方法来从 Basketball 类中获取 self.average 变量的所有实例的列表。然后我将执行 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])

关于python - 如何从类中获取变量的每个实例的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54525876/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com