Error using a constructor in python 2.7

1

I was doing an object-oriented python 2.7 work, I'm quite new to python, and when I run the code it notifies me of the following error:

I am instantiated the object and then serialize it with the "Pickle" module and save it in a file as an object in order to be able to deal with it later with the following code:

def insertarSolicitud():

    #Esta parte pide por consola los datos al usuario que busca empleo

    nombre = raw_input("Introduce tu nombre:")
    apellidos = raw_input("Introduce tus apellidos: ")
    dni = raw_input("Introduce tu D.N.I: ")
    edad = raw_input("Introduce tu edad: ")
    empleo = raw_input("Que empleo buscas")

    nombreFichero = dni + '.dat'

    #Aqui abrimos el fichero
    fichero = file(nombreFichero, 'w')

    #En esta parte hacemos uso de pickle para serializar el objeto empleado y poder escribirlo como objeto
    empleadoAuxiliar = Empleado(nombre, apellidos, dni, edad, empleo) #Usamos el constructor

    # Usamos el modo de codificacion 1 por que es binario y por lo tanto mas efectivo
    pickle_EmpleadoAuxiliar = dumps(empleadoAuxiliar, 1)
    fichero.load(pickle_EmpleadoAuxiliar)#lo cargamos en el fichero con el metodo load

    fichero.close()

The constructor is the following:

def __init__(self, nombre, apellidos, dni, edad, tipoEmpleo):
    self.nombre = nombre
    self.apellidos = apellidos
    self.dni = dni
    self.edad = edad
    self.tipoEmpleo = tipoEmpleo

And the imports that I have to the main .py are these:

from PracticaSSII import Empleado
from PracticaSSII import Empresario
from pickle import dump, load, dumps, loads

PS: if someone knows a page where the python OOP is explained, I would be very grateful

    
asked by MrAlbertusFarray 18.03.2017 в 23:18
source

1 answer

2

This problems as indicated by the error itself is because you are calling a module (file .py ) not a class, method or function contained in it. For example, Empleado in your case must be a class contained within the module called PracticaSSII.py

If your module is called Empleado.py and you try to do what you do, it throws that error at you. I do not know if this is your case, if not, I recommend you edit the question and add the full content of PracticaSSII and the structure of the folder where these files are to see if we can find out what is happening.

To clarify it a bit you should have the following structure:

  • Within the same folder have the files PracticaSSII.py and the module where you call you have the function insertarSolicitud() , for my example I have called main.py .

  • The content of PracticaSSII.py should be something like this:

    class Empleado():
        def __init__(self, nombre, apellidos, dni, edad, tipoEmpleo):
            self.nombre = nombre
            self.apellidos = apellidos
            self.dni = dni
            self.edad = edad
            self.tipoEmpleo = tipoEmpleo
    
    class Empresario():
        #Aquí va el contenido de la clase, al desconocerlo uso pass.
        pass
    
  • The main.py (in your case I do not know what you call it) has the function insertarSolicitud , there are some changes since you use wrong pickle to serialize the data and that I explain now later:

    from PracticaSSII import Empleado
    from PracticaSSII import Empresario
    from pickle import dump, load
    
     def insertarSolicitud():
    
        #Esta parte pide por consola los datos al usuario que busca empleo
    
        nombre = raw_input("Introduce tu nombre:")
        apellidos = raw_input("Introduce tus apellidos: ")
        dni = raw_input("Introduce tu D.N.I: ")
        edad = raw_input("Introduce tu edad: ")
        empleo = raw_input("Que empleo buscas")
    
        nombreFichero = dni + '.dat'
    
        #Aqui abrimos el fichero en modo binario
        fichero = file(nombreFichero, 'wb')
    
        #En esta parte hacemos uso de pickle para serializar el objeto empleado y poder escribirlo como objeto
        empleadoAuxiliar = Empleado(nombre, apellidos, dni, edad, empleo) #Usamos el constructor
    
        # Usamos el modo de codificacion 1 por que es binario y por lo tanto mas efectivo
        dump(empleadoAuxiliar, fichero, 1)
        fichero.close()
    
        #Ahora ya tenemos el objeto empleadoAuxiliar guardado en el .dat
        #Si queremos obtener los datos usamos el metodo load de pickle
        #Abrimos el fichero en modo binario, en este caso se uso un dni 11111111A
    
        fichero = open('11111111A.dat', 'rb')
        datos = load(fichero)#lo cargamos en la variable datos con el metodo load
        fichero.close()
    
        #Ahora datos es la instancia de la clase Empleado de antes y podemos recuperar los datos (atributos de la clase):
        print 'Recuperando datos de objeto serializado:'
        print datos.nombre
        print datos.apellidos
        print datos.dni
        print datos.edad
        print datos.tipoEmpleo
    
    insertarSolicitud()
    

You can see the pickle documentation for more information if you want, the dump method pickle allows you to serialize a python object in a file, the first argument is the object in question (in your case EmpleadoAuxiliar ), the second the file where you will save it and the third the mode. If the mode is 1 or higher you should always open the files in binary mode .

The pickle.load method is not used to load the object in a file but to read a string or text file and return the original object, in your case it allows you to recover the employee data from .dat returning the original object .

Keeping all this in mind we can run the program, I leave a capture with the structure of the folder:

    
answered by 19.03.2017 / 08:06
source