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