试图在python中将项附加到列表中,但其行为很奇怪
我有事件,人们可以属于一个事件。所以我有一个事件类,看起来像:试图在python中将项附加到列表中,但其行为很奇怪,python,python-2.7,Python,Python 2.7,我有事件,人们可以属于一个事件。所以我有一个事件类,看起来像: class Event(): name = "" people = [] 我还有一个全局变量来保存所有事件 events = [] 现在,我正在尝试将原始数据处理为事件和参与事件的人员: # If there are missions, add the events for m in wiki.missions: foundEvent = False for e
class Event():
name = ""
people = []
我还有一个全局变量来保存所有事件
events = []
现在,我正在尝试将原始数据处理为事件和参与事件的人员:
# If there are missions, add the events
for m in wiki.missions:
foundEvent = False
for e in events:
if e.name == m:
foundEvent = True
foundPerson = False
for p in e.people:
if p.rawName == person.rawName:
foundPerson = True
if not foundPerson:
e.people.append(person)
print "Added " + person.display + " to " + m + " (" + str(len(e.people)) + ")"
if foundEvent == False:
event = Event()
event.name = m
event.people.append(person)
print "New " + person.display + " to " + m + " (" + str(len(event.people)) + ")"
events.append(event)
event = None
根据我的打印语句,我可以看到谁被添加到现有事件中,以及何时和谁创建新事件。奇怪的是,一个事件中的人数总是增加所有事件中的人数
New Joseph M. Acaba to STS-119 (1)
New Joseph M. Acaba to Soyuz TMA-04M (2)
New Joseph M. Acaba to Expedition 31 Expedition 32 (3)
Added Dominic A. Antonelli to STS-119 (4)
New Dominic A. Antonelli to STS-132 (5)
Added Richard R. Arnold to STS-119 (6)
这对我来说毫无意义,我做错了什么?(我相信有很多)您应该使用实例变量而不是类变量。因此,像这样设置您的类,并修改其余代码以适应它:
class Event:
def __init__(self, name):
self.name = name
self.people = []
这里的重要区别正如您所描述的:实例变量是为类的特定实例设置的,而类变量是为该类的所有实例设置的。您创建的是类变量,而不是实例变量,因此您不断将人员附加到类中,而不是您创建的每个新对象 请尝试以下方法:
class Event():
def __init__(self, name):
self.name = ""
self.people = []
后来
event = Event(m)
event.people.append(person)
你的问题我不清楚。。您是否也可以显示预期的输出??你想做什么?我想知道。。。我的任何类都是如何工作的:-/我想纯属运气:)@Justin808当您分配例如
event.name=m
时,您会创建一个新的实例变量来隐藏该类变量event.people.append()
是另一种情况:它变异类变量。