0
class Player:
    def __init__(self, name, score):
        self.name = name
        self.score = score
    def __str__(self):
        return self.name +" " +str(self.score)

n = int(input())
data = []
for i in range(n):
    name, score = input().split()
    score = int(score)
    player = Player(name,score)
    data.append(player)
sorted(data,key=getattr(player.score,'name'))
for i in range(n):
    print(data[i])

I am trying to sort a list by using the getattr function. When I try to pass the object in the arguments list I get the following error:

Traceback (most    recent call last):
  File    "C:/Users/raghu/.PyCharmCE2018.2/config/scratches/demo2.py", line 15,    in <module>    sorted(data,key=getattr(player.score,'name'))  
AttributeError: 'int' object has no attribute 'name'

'int' object has no attribute name

khelwood
  • 46,621
  • 12
  • 59
  • 83
  • 1
    What do you expect the line `sorted(data,key=getattr(player.score,'name'))` to do? `player` is the last `Player` instance that you created in the `for` loop, so `player.score` is just an `int`. Do you mean to use [`operator.attrgetter`](https://docs.python.org/3/library/operator.html#operator.attrgetter)? – Brian Apr 13 '20 at 00:02
  • `getattr(player.score,'name')` means get the `name` attribute from the `player.score`. Whatever you meant to do, this is not how you do it. – khelwood Apr 13 '20 at 00:03
  • 1
    Does this answer your question? [How to sort a list of objects based on an attribute of the objects?](https://stackoverflow.com/questions/403421/how-to-sort-a-list-of-objects-based-on-an-attribute-of-the-objects) – Brian Apr 13 '20 at 00:05
  • Hi Brian, yes i want to use operator.attrgetter...could you help – Raghuvendra Kaushik Apr 13 '20 at 12:51
  • i wanted to sort the list by taking player's score as a key and please help me to know how to use this method "getattr" in sorted(data,key=getattr(player.score,'score')) – Raghuvendra Kaushik Apr 13 '20 at 12:55

0 Answers0