【发布时间】: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