Python - 重用相同的字典,同时只更改赋值的对象

时间:2015-07-07 08:11:38

标签: python object dictionary

假设我有这段代码:

for obj in self.objects:
  template = obj
  # Exact values are only numbers (float, int) and or strings
  dct = {
    'a': template.id,
    'b': template.some_other_value,
    'c': template.some_other_value2,
  }
  some_other_obj.use_dct(dct) # Do something with it
  for obj2 in obj:
    # reuse same dictionary, 
    #but regenerate values from another object
    template = obj2 
    some_other_obj.use_dct(dct)

现在执行此操作,将保留旧值,obj2将获得与obj具有相同值的相同字典。是否有可能以某种方式重新生成该字典,所以一切都是相同的,除了template指向另一个对象并且将重生"另一个对象的值?或者我是否必须手动指定具有相同键的另一个字典并用另一个对象填充它?

2 个答案:

答案 0 :(得分:0)

如果没有明确指定值,则无法为dict重新赋值。

你能做的就是写一个能在你需要的时候为你做的功能:

def update_dict_from_obj(dct, obj):
  dct.update({
    'a': obj.id,
    'b': obj.some_other_value,
    'c': obj.some_other_value2,
  })

for obj in self.objects:
  # Exact values are only numbers (float, int) and or strings
  dct = {}
  update_dict_from_obj(dct, obj)
  some_other_obj.use_dct(dct) # Do something with it
  for obj2 in obj:
    # reuse same dictionary, 
    #but regenerate values from another object
    update_dict_from_obj(dct, obj2)
    some_other_obj.use_dct(dct)

或者您可以重写some_other_obj.use_dct来接受您的对象而不是字典

答案 1 :(得分:0)

在我看来,就像你在尝试使用字典一样,当你真正想要的东西完全不同时。

那"某事"应该存储对象的引用,然后使用属性名称以外的名称返回该对象的属性。 (这似乎是一个关键要求,否则你只是使用obj本身,对吗?)

那么为什么不创建一个能够做你想做的事情的课程呢?

class AbcClass:
    def __init__(self, in_object):
        self.obj = in_object

    def dictionary(self):
        obj = self.obj
        return dict(a = obj['id'], b = obj['foo'], c = obj['bar'])

def use_dct(dct):
    print "ID: %s" % dct['a']

objects = [
        dict(id = 1, foo = 'foo', bar = 'bar'),
        dict(id = 2, foo = 'baz', bar = 'qux')
        ]

for obj in objects:
    use_dct(AbcClass(obj).dictionary())

这会产生输出:

ID: 1
ID: 2

你也可能会非常想象,make the object itself into an iterator。 (但这可能会超出要求。)