简体   繁体   中英

How to get list of every instance of variable from class?

I am trying to find a way to get a list of all instances of the self.average variable from the Basketball class. I will then do max(list) to get the maximum value.

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())

You can create a list and store all the instances of the class in it. Then, you can pull all the average values from the list and get the max from them. I would use a list comprehension like this:

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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM