Skip to main content
 首页 » 编程设计

Python 类不适用于排序函数

2025年05月04日10Renyi-Fan

我是 python 的新手,我正在阅读 python 文档和给定的示例 http://docs.python.org/2/howto/sorting.html#key-functions我被卡住了,我不明白它是如何工作的。

我正在使用 eclipse Pydev 来运行这段代码..

class Student: 
 
    student_object = [ 
                  ('john', 'a', 15), 
                  ('as', 'C', 12), 
                  ('dave', 'B', 10) 
                  ] 
 
    def __init__(self, name, grade, age): 
        self.name = name 
        self.grade = grade 
        self.age = age 
 
 
    def __repr__(self): 
        return repr((self.name, self.grade, self.age)) 
 
 
 
print sorted(Student.student_object, key=lambda Student: Student.age)  

错误

Traceback (most recent call last): 
  File "C:\Users\user1\workspace\demPython\src\ru.py", line 26, in <module> 
    print sorted(Student.student_object, key=lambda Student: Student.age)  
  File "C:\Users\user1\workspace\demPython\src\ru.py", line 26, in <lambda> 
    print sorted(Student.student_object, key=lambda Student: Student.age)  
AttributeError: 'tuple' object has no attribute 'age' 

类和方法在 python 中是如何工作的?为什么这段代码不起作用??

编辑

But i changein last line and replace with given line

print sorted(Student.student_object, key=lambda student: student[0]) 

它正在工作并给我输出 [('as', 'C', 12), ('dave', 'B', 10), ('john', 'a', 15)]

请您参考如下方法:

它不起作用,因为 student_object 中的项目不是您的 Student 类的实例,它们只是普通的元组。这就是错误是 'tuple' object has no attribute 'age' 的原因。

您需要先创建学生对象:

class Student(object): 
 
    def __init__(self, name, grade, age): 
        self.name = name 
        self.grade = grade 
        self.age = age 
 
    def __repr__(self): 
        return '{0.name} {0.grade} {0.age}'.format(self) 
 
students = [Student('john','a',15), Student('as','C',12), Student('dave','B',10)] 
print sorted(students, key=lambda x: x.age)