【问题标题】:Automatically add python objects to a dictionary自动将 python 对象添加到字典中
【发布时间】:2018-09-09 17:44:49
【问题描述】:

我有一个类,其中包含程序中其他地方使用的信息,其中定义了许多实例。我想将所有这些添加到字典中,并将它们的 name 属性作为键(见下文),以便用户可以访问它们。

因为我经常制作新的此类对象,有没有办法以相同的方式自动将它们添加到字典中?或者当然是一个列表,之后我可以迭代添加到字典中。

简化示例:

class Example:
    def __init__(self, name, eg):
        self.name = name 
        self.eg = eg

a = Example("a", 0)
b = Example("b", 1)
c = Example("c", 2)
# etc...

# Adding to this dictionary is what I'd like to automate when new objects are defined
examples = {a.name : a,
            b.name : b,
            c.name : c,
            # etc...
            }

# User choice
chosen_name = raw_input("Enter eg name: ")
chosen_example = examples[chosen_name]

# Do something with chosen_example . . . 

我对 python 很熟悉,但对类没有太多了解,所以我不确定什么是可能的。具有相似结果的替代方法也很好,在此先感谢!

【问题讨论】:

  • 在构造函数中添加examples[self.name] = self...

标签: python class object dictionary


【解决方案1】:

我过去做过的一件事是让对象将自己添加到类字典中:

class Example:
    objects = {}

    def __init__(self, name, eg):
        Example.objects[name] = self  # self.objects also works
        ...
...
Example.objects[chosen_name]

【讨论】:

    【解决方案2】:

    您可以将 dict 传递给您创建的所有对象,如下所示:

    class Example:
        def __init__(self, name, eg, all_examples):
            self.name = name 
            self.eg = eg
            all_examples[name] = self
    
    all_examples = {}
    a = Example("a", 0, all_examples)
    b = Example("b", 1, all_examples)
    c = Example("c", 2, all_examples)
    
    print(all_examples)  
    

    【讨论】:

      【解决方案3】:

      下面的示例应该是您需要的。

      __init__中,将你的对象保存到类变量=Example._ALL_EXAMPLES,然后你可以通过Example._ALL_EXAMPLES访问它,即使还没有创建这个类的任何实例(它返回{})。

      我认为我们应该避免在这里使用全局变量,所以使用类变量会更好。

      class Example:
          _ALL_EXAMPLES = {}
          def __init__(self, name, eg):
              self.name = name
              self.eg = eg
              Example._ALL_EXAMPLES[self.name] = self
      print(Example._ALL_EXAMPLES)
      a = Example("a", 0)
      b = Example("b", 1)
      c = Example("c", 2)
      # etc...
      
      print(Example._ALL_EXAMPLES)
      

      输出:

      {}
      {'a': <__main__.Example object at 0x01556530>, 'b': <__main__.Example object at 0x015564D0>, 'c': <__main__.Example object at 0x01556A50>}
      [Finished in 0.163s]
      

      【讨论】:

      • 如果你不想硬编码类名:type(self)._ALL_EXAMPLES[...]
      • @VPfB 我认为只有当 _ALL_EXAMPLES 是 int/string/float 等时它才会起作用。而且我相信这种硬编码会给我们带来好处,即使没有创建任何实例,我们也可以获得一个默认值 = {}。
      • 只有子类有区别。没有指定应该在哪里注册子类的实例。没关系,这只是一个评论,你的回答很好。
      猜你喜欢
      • 1970-01-01
      • 2017-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-08
      • 2015-01-13
      • 1970-01-01
      相关资源
      最近更新 更多