Results 1 to 3 of 3

Thread: Python help. AttributeError: 'NoneType' object has no attribute

  1. #1
    Join Date
    Jan 2015
    Beans
    2

    Angry Python help. AttributeError: 'NoneType' object has no attribute

    so i have this little program

    Code:
    class MyTodos:
        def __init__(self):
            self.list = []
    
    
        def add(self, todo):
            self.list.append(todo)
    
    
        def filter(self, s):
            l = []
            for i in self.list:
                if i.find(s) != -1:
                    l.append(i)
            return l
    
    
    
    
    todos = MyTodos()
    todos.add("prepare fp").add("learn python").add("learn JS")
    for todo in todos.filter("learn"):
        print(todo)
    and i get this error:

    Code:
    todos.add("prepare fp").add("learn python").add("learn JS")
    AttributeError: 'NoneType' object has no attribute 'add'
    how can i fix it? i don't understand why after performing this:
    Code:
    todos.add("prepare fp")
    todos becomes a NoneType

  2. #2
    Join Date
    Jul 2007
    Location
    Poland
    Beans
    4,499
    Distro
    Ubuntu 14.04 Trusty Tahr

    Re: Python help. AttributeError: 'NoneType' object has no attribute

    todos stays todos just fine.
    You have chained function calls yet add() returns nothing so it stops being about todos after the very first step

    Code:
    todos.add("prepare fp").add("learn python").add("learn JS")
    =
    some_obj.add("learn python").add("learn JS")
    =
    None.add("learn python").add("learn JS")
    what would some_obj be? it's not todos, that's for sure.
    add("learn python") is expected to be a method of the object coming from todos.add("prepare fp") but it's going to be None, because the function in question doesn't return anything.
    and add("learn JS") does the same with the result of add("learn python")

    add() in this form is to be executed only once at a time.

    Code:
    todos = MyTodos()
    todos.add("prepare fp")
    todos.add("learn python")
    todos.add("learn JS")
    in order to make add() chainable you'd have to add return self to it
    Last edited by Vaphell; January 22nd, 2015 at 11:19 PM.
    if your question is answered, mark the thread as [SOLVED]. Thx.
    To post code or command output, use [code] tags.
    Check your bash script here // BashFAQ // BashPitfalls

  3. #3
    Join Date
    Jan 2015
    Beans
    2

    Re: Python help. AttributeError: 'NoneType' object has no attribute

    thank you very much.

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •