[Tutor] __init__ doesn't seem to be running

Cameron Macleod cmacleod170 at googlemail.com
Fri Mar 15 23:25:33 CET 2013


I added the "self." to both the references to tasks and then I added the
print statement to the __init__ function and I got the dreaded NameError of
death:


Traceback (most recent call last):
  File "C:\Python33\todo.py", line 6, in <module>
    class todo:
  File "C:\Python33\todo.py", line 31, in todo
    self.tasks.append(line.strip())
NameError: name 'self' is not defined

I then moved the entirety of the code that appeared outside of the
functions but within the class into the writeTask function, this produced
the longed after print statement and no errors, but was inappropriate for
the task in hand. So I re-jiggled most of it into the __init__ method and
left the call to writeTask outside of the class, passing in the argument
main.todoList . This gave me the print statement (the init is running now!)
but also this error:


Traceback (most recent call last):
  File "C:\Python33\todo.py", line 34, in <module>
    main.writeTask(main.todoList)
AttributeError: 'todo' object has no attribute 'todoList'

I fixed this with an attachment to self on the todoList object, but then
got this error instead.

Traceback (most recent call last):
  File "C:\Python33\todo.py", line 34, in <module>
    main = todo()
  File "C:\Python33\todo.py", line 14, in __init__
    for line in todoList:
NameError: global name 'todoList' is not defined

My code now looks something like this:

class todo():
    def __init__(self):
        self.tasks = []
        print("Hello")
        try:
            self.todoList = open('todo.txt', 'r+')
        except IOError:
            self.todoList = open('todo.txt', 'w')
        for line in todoList:
            self.tasks.append(line.strip())


    def writeTask(todoList):
        name = input("Please enter the task > ")
        desc = input("Please enter a short description (optional) > ")
        while True:
            try:
                imp = int(input("How important is this task? 1-100 > "))
                break
            except TypeError:
                imp = int(input("How important is this task? 1-100 > "))
        if imp > 100:
            imp = 100
        elif imp < 1:
            imp = 1
        todoList.write("\"" + name + "\",\"" + desc + "\",\"" + str(imp) +
"\"")
        print("Task written!")


main = todo()
main.writeTask(main.todoList)

It's recognising todoList as global now which is better than not being
acknowledged at all, but why would it not be defined?

(Sorry if this came up twice, wasn't sure whether or not I'd replied to all)


On Fri, Mar 15, 2013 at 9:42 PM, Hugo Arts <hugo.yoshi at gmail.com> wrote:

> On Fri, Mar 15, 2013 at 9:21 PM, Cameron Macleod <
> cmacleod170 at googlemail.com> wrote:
>
>> Hello everyone, I'm using Python 3.3 and am trying to write a simple
>> to-do list program. I have a class which runs pretty much everything called
>> todo and the __init__ method doesn't seem to be running.
>>
>> class todo():
>>     def __init__(self):
>>         tasks = []
>>
>>     def writeTask(todoList):
>>         name = input("Please enter the task > ")
>>         desc = input("Please enter a short description (optional) > ")
>>         while True:
>>             try:
>>                 imp = int(input("How important is this task? 1-100 > "))
>>                 break
>>             except TypeError:
>>                 imp = int(input("How important is this task? 1-100 > "))
>>         if imp > 100:
>>             imp = 100
>>         elif imp < 1:
>>             imp = 1
>>         todoList.write("\"" + name + "\",\"" + desc + "\",\"" + str(imp)
>> + "\"")
>>         print("Task written!")
>>     try:
>>         todoList = open('todo.txt', 'r+')
>>     except IOError:
>>         todoList = open('todo.txt', 'w')
>>     for line in todoList:
>>         tasks.append(line.strip())
>>     writeTask(todoList)
>>     todoList.close()
>>
>> main = todo()
>>
>> Whenever I run this, I get the error:
>>
>> Traceback (most recent call last):
>>   File "C:\Python33\todo.py", line 8, in <module>
>>     class todo():
>>   File "C:\Python33\todo.py", line 34, in todo
>>     tasks.append(line.strip())
>> NameError: name 'tasks' is not defined
>>
>> Indicating that __init__ hasn't run since that is the initialization for
>> tasks. I had always understood that __init__ was the equivalent of a
>> constructor, and should be run at the instantiation of any class.
>>
>
> That's not what it indicates, you should assume less and debug more. If
> you add a print statement in __init__, I can guarantee that you will see it
> executed. Go, try it now, don't assume I'm right ;)
>
> Now, the only thing that this error actually indicates is that "tasks"
> doesn't exist when writeTask is being executed. In both __init__ and
> writeTask, the "tasks" variable is function-local: it exists only for the
> duration of the function. What you want is to attach tasks to your object
> instance, which you do through "self". self is the reference to the current
> instance, much like the this pointer in Java or C++. So if you do:
>
> class Todo:
>     def __init__(self):
>         self.tasks = []
>
>     def write_task(self, task):
>         # other code around here
>         self.tasks.append(line.strip())
>
> everything will be fine.
>
> HTH,
> Hugo
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130315/4c760975/attachment.html>


More information about the Tutor mailing list