在字典值中存储对象

时间:2018-03-14 18:34:51

标签: python object dictionary memory storage

class Draw():
  '''Class using, for example opengl, to display something on the screen'''
  def add(self,size,file_name):
    file_name= file_name
    size = size
class Image(Draw):
  def __init__(self,size,file_name):
    self.size = size
    self.add(self.size,file_name)

class Gui():
  file_names = ['a.jpg','b.jpg']
  images = {}
  def __init__(self):
    for e in self.file_names:
      self.image = Image((50,50),file_name=e)
      self.images[e] = self.image
  def print_size(self):
    print(self.image.size)
a = Gui()
a.print_size() #this gives me a proper (50,50) size
for e in a.images.values():
  print(e.size) #this gives me wrong size

这是我的代码的简化版本。我没有将对象存储在字典值中的经验。 我的问题是:这是正常的,我没有访问字典中存储对象的正确属性?在这个示例中一切正常,但这是编写代码的错误方法吗?

1 个答案:

答案 0 :(得分:0)

我运行你的代码,它可以正常工作。在终端有印刷

  

(50,50)

     

(50,50)

     

(50,50)

你有没有想到别的什么?现在我将尝试解释一些事情。

class Draw():
  '''Class using, for example opengl, to display something on the screen'''

我可能不完全理解它应该如何工作,但是如果你想在add方法中保存大小和file_name,你就会使用self。在变量之前,它看起来像

  def add(self,size,file_name):
    self.file_name = file_name
    self.size = size

class Image(Draw):
  def __init__(self,size,file_name):
    self.size = size
    self.add(self.size,file_name)

class Gui():
    file_names = ['a.jpg','b.jpg']
    images = {}
  def __init__(self):

现在,在每次迭代中,您都会创建具有相同大小(50,50)的新图像,但不同的文件名并确定要映射。

    for e in self.file_names:
      self.image = Image((50,50),file_name=e)
      self.images[e] = self.image

在上面的init方法循环中对self.image你基于file_names(' b.jpg')分配你创建的最后一个图像,所以self.image和self.images [' b .jpg']指向同一个对象。

方法print_size打印self.image / self.images [' b.jpg']的大小,即(50,50)

  def print_size(self):
    print(self.image.size)

a = Gui()
a.print_size() #this gives me a proper (50,50) size

现在你迭代你的图像。有2个:带有file_name' a.jpg'第二个是在' b.jpg'之前已经打印过的。两者的大小相同(50,50)。

for e in a.images.values():
  print(e.size) #this gives me wrong size

我希望我澄清一点,它会帮助你

相关问题