我看到了一些关于制作引用同一词典其他部分的词典的SO问题,但无论何时首次创建词典,它们似乎都是静态返回。有没有办法做到这一点并保持活力?
像这样:
# Lets just say we have a barn with lots of animals
# and the pigs always eat 2 chickens, so there has to always be 2 chickens per pig
def make_barn():
barn = {'pig': 0, 'cow': 0, 'chicken': 2*barn['pig']}
return barn
这样:
barn['pig'] = 3
print barn
将打印此:
{'pig':3, 'chicken':6, 'cow':0}
我尝试使用lambda函数或类,但我试图将其作为一个巨大的字典,以便在multiprocessing
模块中的进程之间传递,而该模块似乎不喜欢lambda
或class
结构。
编辑:
我尝试使用多处理脚本中给出的答案,但它似乎是不可选择的:
import multiprocessing as mp
import random
from UserDict import UserDict
class Barn(UserDict):
'''Barn automatically sets correct values for chickens.
TBD: What to do if chickens get changed?'''
def __init__(self, *args, **kw):
UserDict.__init__(self, *args, **kw)
pigs = self.data.get('pigs', None)
if pigs is not None:
self.data['chicken'] = pigs * 2
def __setitem__(self, name, value):
if name == 'pigs':
self.data['chicken'] = value * 2
self.data[name] = value
def count_animals(barn_record):
for animal in random.randrange(0,10,1):
barn_record['pigs'] = animal
# We need this to 'if __name__ == '__main__':' business to avoid having too many farms created continuously
# See here : https://stackoverflow.com/questions/1923706/multiprocessing-launching-too-many-instances-of-python-vm
if __name__ == '__main__':
manager = mp.Manager()
barn_record = manager.dict({'pigs':3,'cows':2})
farm = mp.Process(target = count_animals, args=(manager,))
farm.start()
print barn_record
可能是这样的吗?使用Python 2.7进行测试。
from UserDict import UserDict
class Barn(UserDict):
'''Barn automatically sets correct values for chickens.
TBD: What to do if chickens get changed?'''
def __init__(self, *args, **kw):
UserDict.__init__(self, *args, **kw)
pigs = self.data.get('pigs', None)
if pigs is not None:
self.data['chicken'] = pigs * 2
def __setitem__(self, name, value):
if name == 'pigs':
self.data['chicken'] = value * 2
self.data[name] = value
if __name__ == '__main__':
b = Barn(cows=1, pigs=2)
print b
b['pigs'] = 3
print b
运行应该会产生这样的结果:
{'cows': 1, 'chicken': 4, 'pigs': 2}
{'cows': 1, 'chicken': 6, 'pigs': 3}