Python 在字典值中存储对象

Python 在字典值中存储对象,python,object,dictionary,memory,storage,Python,Object,Dictionary,Memory,Storage,这是我的代码的简化版本。我没有在字典值中存储对象的经验。 我的问题是:我没有访问字典中存储对象的正确属性,这正常吗?在本示例中,一切正常,但这是一种错误的代码编写方式吗?我运行了您的代码,它正常工作。在终端上有印刷品 (50,50) (50,50) (50,50) 你还期待什么吗?现在我将尝试解释一些事情 class Draw(): '''Class using, for example opengl, to display something on the screen''' def

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

我运行了您的代码,它正常工作。在终端上有印刷品

(50,50)

(50,50)

(50,50)

你还期待什么吗?现在我将尝试解释一些事情

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方法中保存大小和文件名,您应该使用self。在变量之前,所以看起来

class Draw():
  '''Class using, for example opengl, to display something on the screen'''
现在,在每次迭代中,您都会创建具有相同大小(50,50)的新图像,但文件名和assing与map不同

  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):
在上面的init方法中,对self.image进行循环,将根据文件名('b.jpg')创建的最后一个映像分配给self.image,因此self.image和self.images['b.jpg']指向同一个对象

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

现在,您可以对图像进行迭代。共有2个:一个文件名为“a.jpg”,另一个文件名为“b.jpg”。它们的大小都相同(50,50)


我希望我澄清一点,它将帮助您

这不是问题所在,但是您的
add
方法完全没有任何作用。感谢您的贡献。类Draw()是抽象的,我应该在其中使用self-instance。我用我的类Draw()替换Kivy类Widget()及其父类:只是为了让代码看起来更简单。我想知道我是否在这里发布的代码中做了所有正确的事情。你没有说你期望的输出是什么。此外,您可以创建类Draw的实例,因此它不是Abstract。如果您想在python中创建抽象类,请检查模块
    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