我有一個問題,我無法解決。這是我的代碼:AttributeError:'NoneType'對象沒有屬性'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
當我使用chain.get_nth(4)
,例如,它表明:
AttributeError: 'NoneType' object has no attribute 'name'
.
這裏是我的代碼後,我改變了它:
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
但它仍然不起作用。爲什麼它不起作用,我該如何解決它?非常感謝你。
什麼是調用代碼? –
chain = PeopleChain(['a','b','c']) chain.get_nth(4) – user56309
鏈中是否有足夠的人? – user2357112