Python 类不适用于排序函数

标签 python python-2.7

我是 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)

关于Python 类不适用于排序函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20536961/

相关文章:

python - while 循环用户输入?

python - 如何在模块中导入 lib 文件夹

python-2.7 - ImportError : No module named 'skimage' , 但我安装了所有依赖项和 scikit-image

python - 是否可以从 python 中的 tar 包中提取单个文件

python - 模拟 xlsxwriter 中的自动调整列

python - 狮身人面像 : force rebuild of html, 包括 autodoc

python - 值错误 : Attempted relative import in non-package

python - 尝试 google voice api 但在客户端模块上收到 ImportError

python - 对多个字段执行 OR 或将这些字段值组合成单个字段名是否更高效

python - 我可以在 Jupyter 笔记本中使用 Dataflow for Python SDK 吗?