1

I am starting with Python and struggling with populating a dictionary with class objects. My goal is to fill dictionary with device definitions and create interfaces for all devices. The problem is when I try to populate internal list with Interface class objects, all objects in the devices dictionary have the same interface definition in their lists, what is surely not right - interface definitions must be unique. In this example structure is generated for 2 devices. one of them has definition of a single interface Gi1/1, but outputs show that both devices have the same contents in the interfaces list. The source code follows:

class PE:
    interfaces = []
    def __init__(self, name):
        self.name = name
        print('creating device',self.name)

class Interface:
   def __init__(self, name):
        self.name = name

devices = {}
devices['bbr01'] = (PE('bbr01'))
devices['bbr02'] = (PE('bbr02'))
print('let\'s create an interface in  bbr01\'s list')
devices['bbr01'].interfaces.append(Interface('Gi1/1'))
print('what do we have in  bbr01\'s list?')
print(devices['bbr01'].interfaces[0].name)
print('what do we have in  bbr02\'s list?')
print(devices['bbr02'].interfaces[0].name)

Output:

    creating device bbr01
creating device bbr02
let's create an interface in  bbr01's list
what do we have in  bbr01's list?
Gi1/1
what do we have in  bbr02's list?
Gi1/1
Dvalin Swamp
  • 315
  • 1
  • 2
  • 9
  • 2
    The question title sounds simple enough, the question itself is pretty long winded and complicated. Could you create a [MCVE](http://stackoverflow.com/help/mcve) by decoupling the actual problem and its nature from your specific code? – timgeb Mar 10 '16 at 10:14
  • Sanitized most of the data fields - now it is pretty compact, and still shows the problem – Dvalin Swamp Mar 10 '16 at 10:32

1 Answers1

0

The interfaces member is of class level, not instance.

You need to change it to:

class PE(object):
    def __init__(self, name):
        self.name = name
        self.interfaces = []
        print('creating device',self.name)
Alexander Trakhimenok
  • 6,019
  • 2
  • 27
  • 52