I am writing some genetic algorithms in python. Currently I was looking at a book that has java code, so but eventually I am trying to write my own Adaptive Genetic algorithm to optimize neural network parameters and layers, and all my neural network code is in python using keras...so I am just writing my own python code that is equivalent to the books java code.
The problem I am having with the way I have it set up currently, is that the constructor always initializes the object to the constructor in the first statement.
From what I have seen from other questions similar to this, you can use classmethods to do this...and you call also do something with ...isinstanceOf method...and you can do something with init method *args and **kwargs...and I thought you could do something with NoneType parameters which is what I am trying to do...but I have been messing with it on and off and cannot seem to get it to work without adding additional boolean arguments which I would prefer not to do.
What are peoples preferred methods to solving the multiple constructor problem, and can you do it the way I am trying to?
An example of where I am trying to use multiple constructors.
class Individual(object):
#Object Initialisation-->Generally called a constructor
#In python, a variable prefixed with _ is effectively private
def __init__(self, chromosome, chromosomeLength, bool1):
if(chromosomeLength is not None and bool1==False):
self.chromosomeLength = chromosomeLength
self.fitness = -100
self.chromosome = np.empty(chromosomeLength)
for gene in range(self.chromosomeLength):
if(0.5 < np.random.randint(2)):
#self.setGene(gene,1)
#cls.chromosome[gene] = 1
self.chromosome[gene] = 1
else:
#self.setGene(gene,0)
#cls.chromosome[gene] = 0
self.chromosome[gene] =0
elif(chromosome is not None and bool1 ==True):
self.chromosome = chromosome
self.fitness = -1
print ("All variable initialized")
Thanks,
Matt
You could probably use factory functions (or methods, if you like to have them in your class) to construct your objects from different sets of variables:
For instance (pseudocode to illustrate the idea)
This can be coupled with the use of default values.