名前でソートしようとしていますが、 'Person'と 'Person'のインスタンス間でError:TypeError: '<'問題がどこにあるのか教えていただけますか?ここに私のコードです。TypeError: '<'はインスタンス間でサポートされていません - オブジェクト
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()
これは演算子を比較するには、クラスのメソッドとして定義する必要があります。この場合、メソッド名は '__lt__'です。 –