Skip to main content
 首页 » 编程设计

python之类型错误 : '' not supported between instances之objects

2025年05月04日26lautakyan007

我正在尝试按名称排序,但它正在输入错误:TypeError: '<' not supported between instances of 'Person' and 'Person'。你能告诉我问题出在哪里吗?这是我的代码。

class Person: 
    def __init__(self, name, year_of_birth, degree): 
        self.name = name 
        self.year_of_birth = year_of_birth 
        self.degree = degree 
        self.mentor = None 
        self.mentees = [] 
 
def create_mentorship(mentor, mentee): 
    mentee.mentor = mentor 
    mentor.mentees.append(mentee) 
 
def get_founder(people): 
    for person in people: 
        if people[person].mentor == None: 
            return people[person] 
 
def print_mentorship_tree(people): 
    person = get_founder(people) 
    print_mentorship_subtree(person) 
 
 
def print_mentorship_subtree(person, level=0): 
    a = [] 
    print((" " * level) + person.name +' (' + str(person.year_of_birth) + ')') 
    for mentee in person.mentees: 
        print_mentorship_subtree(mentee, level + 1) 
        a = sorted(person.mentees) 
 
    >>> people = {} 
    >>> people['Martin'] = Person('Martin', 1991, 'phd') 
    >>> people['Lukas'] = Person('Lukas', 1991, 'phd') 
    >>> people['Tom'] = Person('Tom', 1993, 'mgr') 
    >>> people['Honza'] = Person('Honza', 1995, 'bc') 
    >>> create_mentorship(people['Martin'], people['Tom']) 
    >>> create_mentorship(people['Tom'], people['Honza']) 
    >>> create_mentorship(people['Martin'], people['Lukas']) 
    >>> print_mentorship_tree(people) 

错误:

Traceback (most recent call last): 
  File "so.py", line 38, in <module> 
    print_mentorship_tree(people) 
  File "so.py", line 20, in print_mentorship_tree 
    print_mentorship_subtree(person) 
  File "so.py", line 28, in print_mentorship_subtree 
    a = sorted(person.mentees) 
TypeError: unorderable types: Person() < Person() 

请您参考如下方法:

正如它所说:您不能对 Person 对象进行排序。如果你想让它工作,你必须至少为你的类定义 __lt__ 运算符,使用你想到的任何排序标准——也许按名称的字母顺序?

另一种可能性是简单地编写您自己的函数,并使用 person.mentees.obj_sort 调用它。


此外,我不确定为什么这很重要:您永远不会使用此操作的返回值。您将它存储在局部变量 a 中(顺便说一下,这是一个糟糕的变量名),并且从不使用它。