【问题标题】:Storing Objects in Dictionary Values在字典值中存储对象
【发布时间】:2018-08-23 10:21:18
【问题描述】:
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

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

【问题讨论】:

  • 这不是问题,但您的 add 方法完全没有任何作用。

标签: python object dictionary memory storage


【解决方案1】:

我运行您的代码,它可以正常工作。在终端打印了

(50, 50)

(50, 50)

(50, 50)

你还期待别的吗?现在我将尝试解释一些事情。

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

我可能不完全理解它应该如何工作,但是如果你想在 add 方法中保存 size 和 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 个:文件名为“a.jpg”的一个,第二个在“b.jpg”之前已打印。两者的大小相同,均为 (50, 50)。

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

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

【讨论】:

  • 感谢您的贡献。类 Draw() 是抽象的,我应该在其中使用 self 实例。我用我的类 Draw() 替换了 Kivy 类 Widget() 及其父类:只是为了让代码看起来更简单。我想知道我在此处发布的代码中是否正确执行了其他所有操作。
  • 你没有说你期望的输出。此外,您可以创建类 Draw 的实例,因此它不是抽象的。如果你想在python中创建抽象类,请查看abc模块
猜你喜欢
  • 2012-02-15
  • 2011-04-14
  • 2014-08-11
  • 1970-01-01
  • 2016-07-30
  • 1970-01-01
  • 2012-11-24
  • 1970-01-01
  • 2014-03-04
相关资源
最近更新 更多