当 Python 只应附加到一个列表时,它会附加到两个列表
Posted
技术标签:
【中文标题】当 Python 只应附加到一个列表时,它会附加到两个列表【英文标题】:Python appending to two lists when it should only append to one 【发布时间】:2011-10-14 17:56:54 【问题描述】:我有一个名为 teams 的列表,其中包含两个对象,它们是同一类的对象,它们都有一个“成员”列表。我将分别附加到这些列表中。请参阅 Fight.AddParticipant 但我附加的两个参与者对象似乎最终出现在两个团队对象中,这是意外行为。为什么会这样?
代码:
class Fight:
participants = []
teams = []
attacked = []
fighting = 0
def MakeTeams(self, team):
self.teams.append(team)
def NumParticipants(self, teamnum = None):
if (teamnum != None):
return len(self.teams[teamnum].members)
else:
return len(self.participants)
def AddParticipant(self, participant, team):
self.participants.append(participant)
ref = self.participants[-1]
self.teams[team].members.append(ref)
# print self.teams[1].members[0].name
def SetFighting(self):
self.fighting = self.NumParticipants()
def AnnounceFight(self):
print 'A battle between', self.NumParticipants(), 'fighters has begun!\n\n'
self.AnnounceTeams()
def AnnounceTeams(self):
print ''
for team in self.teams:
print "Team name:", team.name
print "Team morale:", team.morale
for member in team.members:
print member.name
class Participant:
name = ""
race = ""
sex = ""
hp = 0
strength = 0
agility = 0
weapon = ""
alive = True
def __init__(self, name, race, sex, hp, strength, agility, weapon, alive = True):
self.name = name
self.race = race
self.sex = sex
self.hp = hp
self.strength = strength
self.agility = agility
self.weapon = weapon
self.alive = alive
class Team:
name = ""
members = []
morale = 0
def __init__(self, name, morale):
self.name = name
self.morale = morale
Fight = Fight()
Fight.MakeTeams(Team('Smart', 1))
Fight.MakeTeams(Team('Dumb', 1))
Fight.AddParticipant(Participant("Foo", "Human", "Female", 15, 15, 20, "Knife"), 0)
Fight.AddParticipant(Participant("Bar", "Human", "Male", 15, 15, 20, "Sabre"), 1)
Fight.SetFighting()
Fight.AnnounceFight()
【问题讨论】:
原因可能是您的成员变量是类属性而不是实例属性。因此,在 Team 类的所有实例中都可以看到成员的变化。 【参考方案1】:在所有类中,您都希望像这样初始化实例变量:
def __init__(self):
self.participants = []
self.teams = []
self.attacked = []
self.fighting = 0
这样,它们对于每个战斗、参与者、团队都是独立的,而不是为所有战斗、参与者或团队共享。
【讨论】:
【参考方案2】:您已将列表设为类属性,这意味着列表由所有实例共享。这是同一个列表。您应该制作列表实例属性。通过在类的__init__
(构造函数)方法中创建它们来做到这一点。
【讨论】:
【参考方案3】:我认为您的意思是成员成为实例的成员,而是使它们成为类成员。试试这个:
class Team:
name = ""
morale = 0
def __init__(self, name, morale):
self.members = []
self.name = name
self.morale = morale
您可能希望将所有其他变量移动到构造函数中,而不是将它们保留为类变量。类变量由所有实例共享并归类所有。
【讨论】:
以上是关于当 Python 只应附加到一个列表时,它会附加到两个列表的主要内容,如果未能解决你的问题,请参考以下文章