tags:

views:

104

answers:

2
class a(object):
 def __init__(self):
         self.b = 1
         self.c = 2

This gives the error: NameError: name 'self' is not defined

I looked at a previous post, but the error was for a different reason. Any help with this?

+6  A: 

I'm assuming the single space before def __init__(self): is actually a tab in your file and displayer as four spaces by your editor.

However python interprets a tab as 8 spaces, so the following two lines (which are indented by 8 spaces) are seen by python to be at the same level of indentation as the def.

This is exactly why you shouldn't mix tabs and spaces.

sepp2k
I think that would give an IndentationError, as the def requires a body.
Ray
He may have sliced out earlier lines to "give the simplest example."
Nick T
@Ray: Hm, that's true. And I was so sure this was it...
sepp2k
@Nick: Yes and the earlier lines were indented by two tabs. That must be it.
sepp2k
+1  A: 

This is just a guess because you didn't post the actual traceback or code, but if the actual snippet above is giving you problems, it's probably that your indentation is off and the interpreter is interpreting your scoping levels incorrectly.

Benn
Rats, sepp2k types way faster than I do apparently :)
Benn