gpt4 book ai didi

python - 如何使字典在类实异常(exception)部不可变但在 python 中的类实例内部可变

转载 作者:行者123 更新时间:2023-11-28 19:21:11 28 4
gpt4 key购买 nike

我的目标是创建具有独立身份、性别和州等属性的个体群体。人口被定义为一个类别。然后我创建了一个人口类实例,它允许我使用以下方法向人口中添加个人或从人口中删除个人:

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 会引用字典 (population_instance._PopulationClass__population) 并且不能对该字典进行更改。

但是,我希望使用 add2populationremove_from_population 方法向 population_instance 添加和删除个人。我怎样才能避免将此类非法更改传递给类实例?

最佳答案

你应该为访问私有(private)成员创建“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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com