Python只附加到一个列表时附加到两个列表

时间:2011-07-28 01:03:16

标签: python list object append

我有一个名为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()

3 个答案:

答案 0 :(得分:3)

您已将列表作为类属性,这意味着列表由所有实例共享。这是同一个清单。您应该创建列表实例属性。通过在类的__init__(构造函数)方法中创建它们来做到这一点。

答案 1 :(得分:3)

在所有类中,您希望初始化实例变量,如下所示:

def __init__(self):
    self.participants = []
    self.teams = []
    self.attacked = []
    self.fighting = 0

这样,对于每场比赛,参与者,团队而言,它们是分开的,而不是为所有战斗,参与者或团队共享。

答案 2 :(得分:0)

我认为你的意思是成员是一个实例的成员,而是让他们成为类成员。试试这个:

class Team:
    name = ""
    morale = 0

    def __init__(self, name, morale):
        self.members = []
        self.name = name
        self.morale = morale

您可能希望将所有其他变量移动到构造函数中,而不是将它们保留为类变量。类变量由所有实例共享,并由类拥有。

相关问题