Python appending to two lists when it should only append to one

后端 未结 3 881
半阙折子戏
半阙折子戏 2021-01-27 13:43

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

相关标签:
3条回答
  • 2021-01-27 14:31

    You have made the lists as class attributes, which means the lists are shared by all instances. It's the same list. You should make the lists instance attributes. Do that by creating them in the __init__ (constructor) method of the class.

    0 讨论(0)
  • 2021-01-27 14:43

    I think you mean members to be a member of an instance, but instead making them class members. Try this:

    class Team:
        name = ""
        morale = 0
    
        def __init__(self, name, morale):
            self.members = []
            self.name = name
            self.morale = morale
    

    You probably want to move all the other variables into constructors rather than keeping them as class variables. Class variables are shared by all instances and owned by class.

    0 讨论(0)
  • 2021-01-27 14:45

    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.

    0 讨论(0)
提交回复
热议问题