Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the Python error "name 'self' is not defined" mean?

Tags:

python

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

like image 873
Yarin Avatar asked Nov 30 '22 07:11

Yarin


2 Answers

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()
like image 181
Sven Marnach Avatar answered Dec 02 '22 22:12

Sven Marnach


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()
like image 35
Izkata Avatar answered Dec 02 '22 22:12

Izkata