J'ai une question que je ne peux pas résoudre. Ceci est mon code:AttributeError: L'objet 'NoneType' n'a pas d'attribut 'name'?
class Person:
def __init__(self, name):
self.name = name
self.next = None
class PeopleChain:
def __init__(self, names):
if names == []:
self.leader = None
else:
self.leader = Person(names[0])
current_person = self.leader
for name in names[1:]:
current_person.next = Person(name)
current_person = current_person.next
def get_nth(self, n):
"""Return the name of the n-th person in the chain.
>>> chain = PeopleChain(['a', 'b', 'c'])
>>> chain.get_nth(1)
'a'
"""
current_person = self.leader
for i in range(1, n):
if i < n:
current_person = current_person.next
return current_person.name
Lorsque j'utilise chain.get_nth(4)
, par exemple, il montre que:
AttributeError: 'NoneType' object has no attribute 'name'
.
Voici mon code après avoir changé:
def get_nth(self, n):
current_person = self.leader
for i in range(1, n):
if i < n:
current_person = current_person.next
if current_person is None:
raise SomeError #user-defined error
return current_person.name
Mais encore ne fonctionne pas. Pourquoi ça ne marche pas et comment puis-je le réparer? Merci beaucoup.
Quel est le code d'appel? –
chain = PeopleChain (['a', 'b', 'c']) chain.get_nth (4) – user56309
Y at-il vraiment assez de personnes dans votre chaîne? – user2357112