Uso de la función Ordenada de Python en una lista que tiene una clase

I am currently trying to use the built in function Sorted to sort a list with a class attribute called scores.

Here the sorted function works with just a list, it correctly orders the scores in ascending order.

Scores = [1,5,19,0,900,81,9000]


However when I try to apply this function to my list which has a class attribute, An error is returned: AttributeError: 'list' object has no attribute 'Score'

Aquí está mi código:


Cualquier ayuda sería muy apreciada.

Below is my class being initialised and the list RecentScores

class TRecentScore():
  def __init__(self):
    self.Name = ''
    self.Score = 0

RecentScores = [1,5,0]

preguntado el 28 de mayo de 14 a las 12:05

can u show wt RecentScores contains -

see ..Recent scores is list . then how can u call score -

3 Respuestas

You're not using your class what you're actually doing is just declaring a list with some numbers inside and then you're trying to call the attribute Score on that list object.

class TRecentScore():
    def __init__(self, name, scores): = name
        self.scores = scores

recent_scores = TRecentScore('Sorted Scores', [1,5,0])

contestado el 28 de mayo de 14 a las 13:05

In the class definition, you must first take as inputs the name and score in __init__ como se muestra a continuación:

class TRecentScore():
    def __init__(self, Name, Score):
        self.Name = Name
        self.Score = Score

Then only it makes sense to assign name and score inside the class. Next, the RecentScores instancia de la clase TRecentScore has to be instantiated passing the name and score as arguments to the initialisation. This can be done as shown below:

RecentScores = TRecentScore('Recent Scores',[1,5,0])

This will print out the sorted score. Hope this helps!

contestado el 28 de mayo de 14 a las 13:05

If you always want your scores list sorted, you can sort the list in place, using sorted creates a new list:

class TRecentScore():
    def __init__(self, name, score):
        self.Name = name
        self.score = score

RecentScores = TRecentScore("score list", [1,5,19,0,900,81,9000])
print (RecentScores.score)
[0, 1, 5, 19, 81, 900, 9000]

contestado el 28 de mayo de 14 a las 13:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.