1

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())
9
  • 2
    "I am trying to find a way to get a list of all instances of the "self.average" variable from the Basketball class." It is unclear to me what you mean. You need to keep track of the instances you create of a class yourself. Classes do not keep track of their instances automatically. Commented Feb 4, 2019 at 23:39
  • 1
    You can remember all the average values in the constructor... but then again, what do you want to happen if someone changes them, e.g. if you write player1.average=11 after it was instantiated? Commented Feb 4, 2019 at 23:43
  • 2
    Reopening because having a class autotrack its instances is a terrible way to solve this problem (and a terrible way to solve almost any problem for which such autotracking is proposed as a solution). It is almost always better to use explicit container objects. Commented Feb 4, 2019 at 23:50
  • 1
    Karen and Alex are Basketballs? ;¬) Commented Feb 4, 2019 at 23:56
  • 2
    Why don't you store the instances of the class in a list when you create them? Then you can get the max using something like max([i.average for i in instance_list]) Commented Feb 5, 2019 at 0:06

1 Answer 1

2

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])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.