What does Python error mean "name" self "not defined"?

I can’t understand what happened with this very simple snippet :

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

Traceback (last last call): File "prog.py", line 1, to class A (object): file "prog.py", line 5, to self.printme () NameError: name 'self' not defined

+4
source share
4 answers

The following is an explanation of the problem. Maybe you want to try this?

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

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

A class scope is executed only once during class definition. A β€œcall” to a class with A() calls its __init__() constructor. So maybe you really want this:

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

If you plan to run the function every time an instance of the class is created, try the following:

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

This is exactly what he says: self not defined when calling self.printme() . self not magically defined for you in Python; it only works inside a method that has an argument called self . If this helps, try replacing the word self with something else, say foo , in your entire program (because there is no special value for self as an identifier).

+2
source

if you want to print something when creating an instance of an object:

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

Source: https://habr.com/ru/post/1381939/


All Articles