On Fri, Mar 15, 2013 at 9:21 PM, Cameron Macleod <cmacleod...@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
_______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor