简体   繁体   中英

AttributeError: 'NoneType' object has no attribute 'name'?

I have a question that I cannot solve. This is my code:

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

When I use chain.get_nth(4) , for example, it shows that:

AttributeError: 'NoneType' object has no attribute 'name' .

Here is my code after I changed it:

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

But it still doesn't work. Why does it not work and how can I fix it? Thank you very much.

I think you misunderstood.

Your PeopleChain class:

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

Just to say, type(None) is equal to NoneType. Instead of using

self.leader = None

use:

self.leader = []

Try the following code

class ShortChainError(Exception):
    def __init__(self,*args,**kwargs):
        Exception.__init__(self,*args,**kwargs)

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:
        try:
          current_person = current_person.next
          name = current_person.name
        except AttributeError:
          raise ShortChainError("Your Message Here!!!")
    return name

Instead of adding if statement you can add try and catch it's more pythonic way. So your code will become

  if i < n:
    try:
      current_person = current_person.next
      name = current_person.name
    except AttributeError:
      raise ShortChainError("Your Message Here!!!")
return name

Now On running this code like this

PeopleChain(['a', 'b', 'c']).get_nth(4)

It will throw a custom error exception such as

    raise ShortChainError("Your Message Here!!!")
__main__.ShortChainError: Your Message Here!!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM