What does the Python error “name ‘self’ is not defined” mean?

The following should explain the problem. Maybe you will want to try this?

class A(object):
    def printme(self):
        print "A"
a = A()
a.printme()

The name self is only defined inside methods that explicitly declare a parameter called self. It is not defined at the class scope.

The class scope is executed only once, at class definition time. “Calling” the class with A() calls it’s constructor __init__() instead. So maybe you actually want this:

class A(object):
    def __init__(self):
        self.printme()
    def printme(self):
        print "A"
a = A()

Leave a Comment