My objective is to create a population of individuals with attributes like iid, gender and state. The population is defined as a class. I then create a population class instance which allows me to add individuals to and remove individuals from the population using the following:
class PopulationClass(object):
def __init__(self):
self.__population = dict()
self.__iid_counter = 0
self.__removed_individuals = []
def add2population(self, no2add):
import random
iid_counter = self.__iid_counter
for a in range(no2add):
self.__population[iid_counter] = (iid_counter, random.sample(('F', 'M'), 1)[0], 'S')
iid_counter += 1
self.__iid_counter = iid_counter
def remove_from_population(self, key):
self.__removed_individuals.append(self.__population.pop(key))
In the terminal, I do the following:
>>> population_instance = PopulationClass()
>>> population_instance.add2population(5)
>>> population_instance._PopulationClass__population
{0: (0, 'F', 'S'), 1: (1, 'M', 'S'), 2: (2, 'F', 'S'), 3: (3, 'M', 'S'), 4: (4, 'M', 'S')}
>>> population = population_instance._PopulationClass__population
>>> population[5] = 'Illegal changes'
>>> population
{0: (0, 'F', 'S'), 1: (1, 'M', 'S'), 2: (2, 'F', 'S'), 3: (3, 'M', 'S'), 4: (4, 'M', 'S'), 5: 'Illegal changes'}
>>> population_instance._PopulationClass__population
{0: (0, 'F', 'S'), 1: (1, 'M', 'S'), 2: (2, 'F', 'S'), 3: (3, 'M', 'S'), 4: (4, 'M', 'S'), 5: 'Illegal changes'}
I wish that population would refer to the dictionary (population_instance._PopulationClass__population
) and not be able to make changes to that dictionary.
However, I want individuals to be added to and removed from the population_instance
using the add2population
and remove_from_population
methods. How can I avoid such illegal changes from being passed through to the class instance?