class warehouse:
def __init__(self):
self.A={}
self.B={}
self.racks={'A':self.initialize(self.A),'B':self.initialize(self.B)}
def initialize(self,rack):
shelf = dict([ (items,0) for items in range(1,6) ])
for x in range(3):
rack[x+1]=shelf
return rack
def store(self,_id,owner_id,colour,weigth):
import pdb;pdb.set_trace()
empty_position=self.empty_positions(self.store.__name__)[0]
self.racks[empty_position[0]][empty_position[1]][empty_position[2]]= {'id':_id,'owner':owner_id,'colour':colour,'weigth':weigth}
print self.racks
def empty_positions(self,name):
store_list=[]
for rack,shelfs in self.racks.iteritems():
for shelf_number,shelf_objects in shelfs.iteritems():
store_list.append([rack,shelf_number])
for position,value in shelf_objects.iteritems():
if 0==value:
store_list.append([rack,shelf_number,position])
return store_list
obj=warehouse()
val=obj.store(2,34,4,44)
这是一个类仓库我想通过调用类的init方法来创建一个字典。现在我想使用类仓库的相同实例将一些值存储到嵌套字典中。当我调用obj.store( 2,34,4,44)。它会更新字典并给出结果。
{'A': {1: {1: {'colour': 4, 'id': 2, 'owner': 34, 'weigth': 44},
2: 0,
3: 0,
4: 0,
5: 0},
2: {1: {'colour': 4, 'id': 2, 'owner': 34, 'weigth': 44},
2: 0,
3: 0,
4: 0,
5: 0},
3: {1: {'colour': 4, 'id': 2, 'owner': 34, 'weigth': 44},
2: 0,
3: 0,
4: 0,
5: 0}},
'B': {1: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0},
2: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0},
3: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0}
}
}
但我期待:
{'A': {1: {1: {'colour': 4, 'id': 2, 'owner': 34, 'weigth': 44},
2: 0,
3: 0,
4: 0,
5: 0},
2: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0},
3: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0}},
'B': {1: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0},
2: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0},
3: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0}
}
}
它在键'A'和1的所有其他嵌套字典中设置值我尝试放置PDB并对其进行调试,但它显示相同的结果。但是,如果我在终端中执行此操作,那么我会得到我所期望的结果。
Python 2.6.6 (r266:84292, Sep 15 2010, 15:52:39)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> d={'A': {1: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0}, 2: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0}, 3: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0}}, 'B': {1: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0}, 2: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0}, 3: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0}}}
>>> d['A'][1][1]={"some_key":"some_value",}
>>> d
{'A': {1: {1: {'some_key': 'some_value'}, 2: 0, 3: 0, 4: 0, 5: 0}, 2: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0}, 3: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0}}, 'B': {1: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0}, 2: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0}, 3: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0}}}
我不知道我可能遗漏了什么,或者有什么我无法赶上的错误。我正在使用 python 2.6.6 并尝试过这也是 2.7.1。