4
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?

sepp2k
372k56 gold badges687 silver badges687 bronze badges
asked Oct 28, 2010 at 17:36
5
  • 2
    What you have is valid. We need a more complete picture. Commented Oct 28, 2010 at 17:38
  • 1
    The code in the question is valid. By the way, class names begin with a capital letter by convention Commented 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. Commented 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. Commented Oct 28, 2010 at 17:44
  • Does this answer your question? "NameError: name 'self' is not defined" Commented Dec 23, 2021 at 11:02

2 Answers 2

12

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.

answered Oct 28, 2010 at 17:39
Sign up to request clarification or add additional context in comments.

3 Comments

I think that would give an IndentationError, as the def requires a body.
He may have sliced out earlier lines to "give the simplest example."
@Nick: Yes and the earlier lines were indented by two tabs. That must be it.
2

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.

answered Oct 28, 2010 at 17:41

1 Comment

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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.