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?
-
2What you have is valid. We need a more complete picture.nmichaels– nmichaels2010年10月28日 17:38:02 +00:00Commented Oct 28, 2010 at 17:38
-
1The code in the question is valid. By the way, class names begin with a capital letter by conventionpberkes– pberkes2010年10月28日 17:40:10 +00:00Commented Oct 28, 2010 at 17:40
-
1@Nathon: I reverted your edit since the indentation is exactly what's wrong with the code, and fixing the indentation makes the question entirely pointless.sepp2k– sepp2k2010年10月28日 17:43:46 +00:00Commented Oct 28, 2010 at 17:43
-
on which line do you get the NameError (yes, I doubt it's too relevant, but...). Please append the full stacktrace.Adriano Varoli Piazza– Adriano Varoli Piazza2010年10月28日 17:44:00 +00:00Commented Oct 28, 2010 at 17:44
-
Does this answer your question? "NameError: name 'self' is not defined"outis– outis2021年12月23日 11:02:14 +00:00Commented Dec 23, 2021 at 11:02
2 Answers 2
I'm assuming the single space before def __init__(self): is actually a tab in your file and displayed 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.
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.