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
  • 2
    _init__ only has one underscore at the beginning. It needs two. Commented Feb 6, 2018 at 4:15

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.