我的目标是创造一个具有iid、性别和国家属性的个体群体。总体被定义为一个类。然后,我创建一个population类实例,该实例允许我使用以下命令向population添加个人并从population中删除个人:

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))

在终端中,我执行以下操作:
>>> 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'}

我希望这个群体能够参考字典(population_instance._PopulationClass__population),并且不能对字典进行更改。
但是,我希望使用population_instanceadd2population方法将个人添加到remove_from_population中并从中移除。如何避免此类非法更改传递到类实例?

最佳答案

您应该为访问私有成员设置“get”函数

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))
  def getPopulation():
    import copy
    return copy.deepcopy(self.__population)

population_instance = PopulationClass()
population_instance.add2population(5)
population_instance._PopulationClass__population
population = population_instance.getPopulation()
population[5] = 'Illegal changes'
population
population_instance._PopulationClass__population

关于python - 如何使字典在类实异常(exception)部不可变但在python中的类实例内部可变,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24603219/

10-10 14:41