Problem with the use of python classes


When I run my program it gives me this error:


new = colony.Colonia (self .__ tasks, self .__ times)   UnboundLocalError: local variable 'colony' referenced before assignment

my class is the following:

import tareas
import hormiga
import colonia
class inicio:
def __init__(self):
    self.__nHormigas = 20 #mAnts
    self.__veces = 4 #mIter
    self.__generaciones = 500 #mHillsCount
    self.__alfa = 1
    self.__beta = 1 
    self.__p = 0.1 #mEvap
    self.__nTareas = 100
    self.__mColonia = [] #mHills
    self.__tareas = []
    self.__mMejorRuta = []

def getMejorCoste(self):
    return self.__mejorCoste #mBestCost

def getRuta(self):
    return self.__mMejorRuta #mBestPath

def Iniciar(self):
    self.__mejorCoste = float('inf')
    for e in range(self.__nTareas):
        tarea = tareas.Tarea()
    for i in range(self.__generaciones):
        nueva = colonia.Colonia(self.__tareas,self.__veces) #aquí es el error
    #en paralelo??
    for colonia in self.__mColonia:
    self.__mColonia.sort(key=lambda x: x.getMejorCoste())
    if (self.__mColonia[0].getMejorCoste() < self.__mejorCoste):
        self.__mejorCoste = self.__mColonia[0].getMejorCoste()
        self.__mMejorRuta = []
        for tarea in self.__mColonia[0].getMejorRuta():

My file directory contains one called whose constructor is the following:

class Colonia:
def __init__ (self, tareas, n_iteraciones, evaporacion=0.1, n_hormigas=20):
    self.__constanteEvaporacion = evaporacion
    self.__nHormigas = n_hormigas
    self.__iteraciones = n_iteraciones
    self.__evaporacion = 1.0 - evaporacion
    self.__tareas = tareas

    self.__mejorCoste = float('inf')
    self.__mejorRuta = list()
    self.__hormigas = []
    #inicializamos matriz de feromonas
    self.__mFeromonas = [[getValorInicialFeromona()]*len(self.__tareas) for x in range(len(self.__tareas))]
    self.__feromonas = [[0.0]*len(self.__tareas) for x in range(len(self.__tareas))]

my directory.

Any ideas?

Thank you.

asked by XBoss 30.01.2018 в 20:35

1 answer


I have to see the structure of your directories and files, if you do not solve it with what I'm going to comment add it and edit my answer.

Make sure that the directory where the module is found also contains the file , this serves to indicate that the package (directory where the is found) contains python files, otherwise you can not import the modules.

Another cause of the error may be an inadequate import:

if the module is in another package the correct import would be from paquetex.colonia import Colonia and if it is in the same one '' from colony import colony '

the initialization of the object would be like this:

'new = Colony (self .__ tasks, self .__ times)

answered by 30.01.2018 / 22:08