NameError: name 'self' is not defined, even though it is?

The for loop is indented incorrectly resulting in it being outside that method's scope but inside the class' scope. This in turn means that self is not defined.

Python does interpret that loop code in the scope of the class, but without an instance of the object. Sample malformed code:

class Simple(object):
    def __init__(self, a):
        self.a = a

    print("Here we go!")
    for i in xrange(self.a):
        print(i)

Traceback

$ python simple.py
Here we go!
Traceback (most recent call last):
  File "simple.py", line 4, in <module>
    class Simple(object):
  File "simple.py", line 9, in Simple
    for i in xrange(self.a):
NameError: name 'self' is not defined

Tags:

Python

Oop

Class