0

I am confused about instance and class variables in python. I am confused about how this code:

class A:
    def _init__(self):
        print "initializer called"
        #l is an instance variable
        self.l = []
        print len(l)
    def printList(self):
        print len(self.l)

a = A()
print "here"
a.printList()

produces the following output:

here
Traceback (most recent call last):
  File "C:\Python27\a.py", line 16, in <module>
    a.printList()
  File "C:\Python27\a.py", line 10, in printList
    print len(self.l)
AttributeError: A instance has no attribute 'l'

Is the initializer not being called? Why does "here" print, but the print statement in the initializer doesn't? Should 'l' be a class variable? I thought making it an instance variable using 'self' would be sufficient, is that not correct? Am I incorrect about the scope of these variables?

I have looked at these sources, but they didn't help:

Python: instance has no attribute

Python: Difference between class and instance attributes

Python - Access class variable from instance

Python Variable Scope and Classes instance has no attribute

1 Answers1

3

You defined a method named _init__, not __init__. The number of underscores is important. Without the exact correct name, it's just a weirdly named method, not the instance initializer at all. You end up using the default initializer (which sets no attributes). You also have an error in your _init__ (you refer to l unqualified). Fixing the two, your initializer would be:

def __init__(self):    # <-- Fix name
    print "initializer called"
    #l is an instance variable
    self.l = []
    print len(self.l)  # <-- Use self.l; no local attribute named l
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271