Python为同一个类创建不同的变量名称和实例

时间:2016-12-13 10:35:53

标签: python python-3.x variables

我正在尝试创建变量名称,例如:

event1
event2
event3

命名同一类的不同实例。

我在网上搜索,很多人都在建议字典。但据我所知,字典仅适用于成对。我想命名同一个类的不同实例,例如:

class Event:
  def __init__(self, description):
    self.__description = description

event1 = Event('This is event 1')
event2 = Event('This is event 2')
event3 = Event('This is event 3')

有谁知道我怎么能这样做? 提前谢谢。

编辑1:

看来我的问题不够明确。 我不知道需要多少个实例。我将读取文件的长度(文件中的行数),然后创建该类的实例。

编辑2:

我有多条信息可以填写课程。例如:

class Event:
  def __init__(self, name, description, value):
    self.__name = name
    self.__description = description
    self.__value = value

event1 = Event('This is event 1', 'Tom eats apple', '20')
event2 = Event('This is event 2', 'Jerry eats pie', '10')
#......
#(maybe 20 or more)

3 个答案:

答案 0 :(得分:1)

要动态创建多个实例,最好的解决方案是使用如下字典:

class Event:
  def __init__(self, description):
    self.__description = description


events = {}

num_events = 5 # Or whatever

for i in range(num_events):
    events['event{}'.format(i + 1)] = Event('This is event {}'.format(i + 1))

<强>输出:

>>> events
{'event4': <__main__.Event instance at 0x02F70E40>, 'event5': <__main__.Event instance at 0x02F70DF0>, 'event2': <__main__.Event instance at 0x02F70DA0>, 'event3': <__main__.Event
instance at 0x02F70D50>, 'event1': <__main__.Event instance at 0x02F70C60>}

答案 1 :(得分:1)

这是一个班级:

class Event:
    def __init__(self, description):
    self.__description = description

现在我们想要使用从多个列表中获取的条目来创建此类的n个实例:

entries_a = ['input 1', 'input 2', 'input 3']
entries_b = ['something 1', 'something 2', 'something 3']
entries_c = ['a', 'b', 'c']

以下是我们如何组合所有条目(必须具有相同的长度)。

entries = zip(entries_a, entries_b, entries_c)

以下是我们如何为entries创建该类的实例:

instances =  [Event(val_a, val_b, val_c) for val_a, val_b, val_c in entries]

或使用字典:

instances = {(val_a, val_b, val_c): Event(val_a, val_b, val_c) for item in entries}

答案 2 :(得分:1)

使用清单:

class Event:
  def __init__(self, description):
    self.__description = description

event = []
event.append(Event('This is event 0'))
event.append(Event('This is event 1'))
event.append(Event('This is event 2'))
...

因此,您可以存储任意数量的实例,而无需事先知道多少实例。

字典解决方案类似:

event = {}
event[1] = Event('This is event 1')
event[2] = Event('This is event 2')
event[3] = Event('This is event 3')
...

event = {}
event['a'] = Event('This is event A')
event['b'] = Event('This is event B')
event['c'] = Event('This is event C')
...

取决于您希望如何识别它们。