我有一個列表稱爲包含兩個對象,它們是同一類的對象,他們都有一個「成員」列表的團隊。我將逐個追加到這些列表中。請參閱Fight.AddParticipant,但是我追加的兩個參與者對象似乎最終會出現在兩個團隊對象中,這是意想不到的行爲。這是爲什麼發生?Python追加到兩個列表時,它應該只能追加到一個
代碼:
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()
原因可能是您的成員變量是一個類屬性而不是實例屬性。因此,在您的團隊類的所有實例中都可以看到成員變化。 – Marcin