Question

This seems like such a simple question, but there don't seem to be any answers that address my particular issue, which is why the init method never actually initiates the class instance variable 'listlist'.

class PointsList():
    def _init_(self):        
        self.listlist = [None]
    def addtolist(self,item):
        self.listlist.append(item)              
    def getlist(self):
        return self.listlist


a = PointsList()
a.addtolist('Scarlet')
print a.getlist()

Running the above code gives me: AttributeError: PointsList instance has no attribute 'listlist'

The error is traced to line 5 when the 'addtolist' method attempts to add an item to the evidently nonexistent 'listlist' instance variable.

I've checked the indentation many times but it appears to be sound. Is there something wrong with my Python installation? I am using Python v2.7.5 (haven't gotten around to 2.7.6 yet) and the Spyder IDE v2.2.0

Was it helpful?

Solution

Python special methods use two underscores at the start and end; you need to name the initializer __init__, not _init_:

class PointsList():
    def __init__(self):        
        self.listlist = [None]

Underscore characters are usually shown connecting up forming a longer line, but there are two underscores before init, and two after.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top