I am writing an article as a memo while making parts for evolution simulation by Python. The previous article was here (Introduction to Object Orientation-Let's change the internal state of an object)
This time, I made a draft of a method (reproduction) that allows a virtual individual to give birth. The reproduction method uses deepcopy of the copy module.
reproduction.py
#Implementation of reproduction
import copy #Use deepcopy for reproduction.
class SampleIndividual:
def __init__(self,x,y,z):
self.state_x = x
self.state_y = y
self.state_z = z
def mutation(self): #Method for mutation of internal state.
self.state_x = 10
def reproduction(self): #Method to give birth to a child
self.child = copy.deepcopy(self)
self.child.mutation() #Mutation of internal state
return self.child
Below is the output. Properly mother and child are separate instances.
output
mother = SampleIndividual(5,5,5) #Creating a parent
child = mother.reproduction() #Creating a child
print(vars(child))
#=> {'state_x': 10, 'state_y': 5, 'state_z': 5}
print("mother id:{}".format(id(mother))) #Check if it is another instance
print("child id:{}".format(id(child)))
#=> 4453353808
#=> 4453466064
that's all. Thank you for reading.
Recommended Posts