Error when using "self": "NameError: name 'self' is not defined

1

When trying to execute my code, it sends me the following error:

  

[NameError: name 'self' is not defined]

This happens to me every time I use self . This is my code:

from tkinter import*

class __init__(self,contenedor):

    self.e1 = Label(contendeor, text ="Etiqueta1", fg="black", bg="white")
    self.e1.pack()

ventana =Tk()
miInterfaz= Interfaz (ventana)
ventana.mainloop()

How can I solve it?

    
asked by Miguel O'Hara BL 30.08.2017 в 21:27
source

2 answers

3

You are using the special method __init__ as a class name and not as a class method (I do not know what you are trying to do on that line, you may be confusing concepts.).

The __init__ method is in charge of initializing the class, of giving a certain status to your object as soon as it is instantiated. It is executed automatically when the class is instantiated and is something similar to what is known as "constructor" in other languages. In your case, it is responsible for receiving the root instance for your Label as parameter and creating it.

Look at these two questions for more information:

You must use the reserved word class to define a class and def to define methods (such as the __init__ method).

The use of for modulo import * is a very bad practice that you should avoid, even more if you are learning (see PEP 8 ). The code is less readable and can induce errors by overwriting some method by mistake (especially in complex libraries). You will find it often, especially in Tkinter tutorials (partly because of the documentation of effbot. org ), which does not imply that it's not a bad idea, like the famous using namespace std; of C ++ ... :). Nothing happens in a simple example like this, but to avoid taking bad habits, better avoid it. Remember the zen from Python:

  

"Explicit is better than implied"

Instead use one of the following ways:

  • from tkinter import Label, Tk
  • import tkinter

or the most generalized (to save characters):

  • import tkinter as tk

The self parameter is a convention. Instance methods must receive as a first parameter the reference to the instance of the class to which they belong. self is just that, the reference to the instance to which the method belongs. When an instance method is called it is automatically passed. In front of the attributes (as in the __init__ ) they indicate that they are instance attributes.

If we have the class:

class Foo:
    def bar():
        print("Soy un método de la instancia: ", self)

We instantiate and call your method like this:

>>> instancia = Foo()
>>> instancia.bar()
Soy un método de la instancia:  <__main__.Foo object at 0x7f4e0a267080>

This is the same as doing (so you understand what self is):

>>> instancia = Foo()
>>> Foo.bar(instancia)
Soy un método de la instancia:  <__main__.Foo object at 0x7f8436622cc0>

You can see a much more extended explanation in the following publication:

Your code has no more problems, apart from a typo in the first parameter when instantiating Label , it should be like this:

import tkinter as tk

class Interfaz():  #Definición de tu clase llamada Intefaz
    def __init__(self, contenedor):   #Definición de su método __init__ Intefaz
        self.e1 = tk.Label(contenedor, text ="Etiqueta1", fg="black", bg="white")
        self.e1.pack()

ventana = tk.Tk()              #Instancia de la clase Tk.
miInterfaz= Interfaz(ventana)  #Instancia de tu clase Interfaz.
ventana.mainloop()            
    
answered by 30.08.2017 / 22:00
source
1

Class is a reserved word to create a class.

__ init__ serves as a 'contructor' function in other languages. Therefore it must be something like that.

try:
    # Python2
    from Tkinter import * 
except ImportError:
    # Python3
    from tkinter import * 

class Interfaz:

    def __init__(self, contenedor):
        self.e1 = Label(contenedor, text ="Etiqueta1", fg="black", bg="white")
        self.e1.pack()

ventana =Tk()
miInterfaz= Interfaz (ventana)
ventana.mainloop()

Also notice an error in the second container. If you are new to Python, I recommend you start with programs that use the command line, instead of going directly to the graphical interface.

    
answered by 30.08.2017 в 21:45