3

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.

1

3 Answers 3

2

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 = []
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.