如何在类实例外使字典不可变但在python中的类实例内是可变的

时间:2014-07-07 04:48:56

标签: python dictionary

我的目标是创建一个具有iid,性别和州等属性的个体群体。人口被定义为一个阶级。然后,我创建了一个种群类实例,允许我使用以下内容向个体添加个体并从中删除个体:

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并从中删除。如何避免将这些非法更改传递给类实例?

1 个答案:

答案 0 :(得分:0)

您应该为访问私人会员制作“获取”功能

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