user2153627
user2153627

Reputation:

Python Object list keep changing when I change an other object list

I have two different class

class   ircChannel:
   NAME = ""

   def __init__(self):
      self.NAME = NAME

class   ircServer:
   HOST = ""
   PORT = 0
   CHAN = []

   def __init__(self, HOST, PORT):
      self.HOST = HOST
      self.PORT = PORT

   def addChan(self, CHANEL):
      self.CHAN.append(CHANEL)

I am parsing an XML file and create a list of ircServer containing a list of ircChannel

for server in servers
    ircBot.addServer(ircServer(HOST, PORT))
    for channel in channels 
         ircBot.SERVERS[-1].addChan(ircChannel(channel.name))

And when I print the result, I kept getting duplicate

ircBot
   Server 1 -
       Channel1
       Channel2
       Channel3
   Server 2 -
       Channel1
       Channel2
       Channel3

But all I need is

ircBot
   Server 1 -
       Channel1
       Channel2
   Server 2 -
       Channel3

Why doest the two list keep having the same channels when I obviously create two different instances of irsServer and add different channels ?

I tried emptying the list in the init of the ircServer class but it's not working.

Upvotes: 3

Views: 201

Answers (3)

Brian Cain
Brian Cain

Reputation: 14619

The problem is here:

class   ircServer:
   HOST = ""
   PORT = 0
   CHAN = []

These are members of the entire class, not merely a single object (instance) of it. To fix it, move it to the constructor (__init__):

class   ircServer:
   def __init__(self, HOST, PORT):
       self.HOST = HOST
       self.PORT = PORT
       self.CHAN = []

Class members are like scoped global variables. They have some utility, but it doesn't seem like they would be useful to solve this particular problem. If there were any case for it, it might be a default port number:

class ircServer:
    DEFAULT_PORT = 44100
    def __init__(self, HOST, PORT = DEFAULT_PORT):
        self.HOST = HOST
        self.PORT = PORT
        self.CHAN = []

Upvotes: 2

warvariuc
warvariuc

Reputation: 59604

Modify

class   ircServer:
   HOST = ""
   PORT = 0

   def __init__(self, HOST, PORT):
      self.CHAN = []
      self.HOST = HOST
      self.PORT = PORT

   def addChan(self, CHANEL):
      self.CHAN.append(CHANEL)

otherwise CHAN is a class attribute and is the same for all class instances. Doing self.CHAN = [] in __init__ will make CHAN an instance attribute.

Upvotes: 1

John La Rooy
John La Rooy

Reputation: 304205

Lose the class attributes. You are not using them anyway. In fact it's causing your bug because all the instances appear to share the same CHAN list

class   ircServer:
   def __init__(self, HOST, PORT):
      self.HOST = HOST
      self.PORT = PORT
      self.CHAN = []

   def addChan(self, CHANEL):
      self.CHAN.append(CHANEL)

Also consider reading PEP8 and following at least most of the guidelines there

Upvotes: 1

Related Questions