Question

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

I can’t figure out what’s wrong with this very simple snippet:

class A(object):
        def printme(self):
                print "A"

        self.printme()

a = A()

Error output:

 Traceback (most recent call last):   File "prog.py", line 1, in
 <module>
     class A(object):   File "prog.py", line 5, in A
     self.printme() NameError: name 'self' is not defined

Enquirer: Yarin

||

Solution #1:

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()
Respondent: Sven Marnach

Solution #2:

If you’re intending for the function to run each time an instance of the class is created, try this:

class A(object):
    def __init__(self):
        self.printme()

    def printme(self):
        print "A"

a = A()
Respondent: Izkata

Solution #3:

It’s exactly what it says: self is not defined when you call self.printme(). self isn’t magically defined for you in Python; it only works inside a method which has an argument named self. If it helps, try replacing the word self with something else, say foo, throughout your program (because there is really nothing special about self as an identifier).

Respondent: David Z

Solution #4:

if you want to print something when you instantiate the object use:

class A(object):
    def __init__(self):
            self.printme()

    def printme(self):
            print "A"

a = A()
Respondent: catalin.costache

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Most Popular

To Top
India and Pakistan’s steroid-soaked rhetoric over Kashmir will come back to haunt them both clenbuterol australia bossier man pleads guilty for leadership role in anabolic steriod distribution conspiracy