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

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

本文介绍了Python附加到两个列表时只应附加到一个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为团队的列表,其中包含两个对象,这些对象属于同一类,并且它们都有一个成员"列表.我将单独附加到这些列表中.请参阅 Fight.AddParticipant,但我附加的两个参与者对象似乎最终出现在两个团队对象中,这是意外行为.为什么会发生这种情况?

I have a list called teams which contains two objects, these are objects of the same class and they both have a "members" list. I am appending to these lists individually. See Fight.AddParticipant but the two participant objects I'm appending seem to end up in both of the team objects, which is unintended behavior. Why is this happening?

代码:

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()

推荐答案

在你所有的类中,你想像这样初始化实例变量:

In all of your classes, you want to initialize instance variables like this:

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

这样,它们对于每个战斗、参与者、团队都是分开的,而不是为所有战斗、参与者或团队共享.

That way, they are separate for each fight, participant, team instead of shared for all fights, participants, or teams.

这篇关于Python附加到两个列表时只应附加到一个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 03:03