[Tutor] __init__ doesn't seem to be running
Hugo Arts
hugo.yoshi at gmail.com
Fri Mar 15 23:38:25 CET 2013
On Fri, Mar 15, 2013 at 10:25 PM, Cameron Macleod <
cmacleod170 at googlemail.com> wrote:
> 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 must apologize. I did not notice you omitted it. In python, the "self"
does *not* exist implicitly like "this" in Java or C++. In class methods,
the first argument to a method is *always* the current instance, and python
passes it in automatically. By convention, this is called self, but it
could have any name. In other words, when you write this:
main.writeTask(todoList)
python actually interprets it like so:
todo.writeTask(main, todoList)
As you can see, the main instance object is the first argument to the
method, which should be defined like this:
def writeTask(self, todoList):
# code here can use self.stuff
To repeat, the name "self" is not special in Python, it's just that the
first argument to every method called is always the current instance, and
by convention this is always called "self" by programmers. You should add
self to every method in a class, unless it is a @classmethod or
@staticmethod, but those are relatively rare exceptions.
HTH,
Hugo
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130315/a2666ad0/attachment.html>
More information about the Tutor
mailing list