我从Python开始,并努力用类对象填充字典。
我的目标是用设备定义填充字典并为所有设备创建接口。
问题是当我尝试使用Interface类对象填充内部列表时,devices
字典中的所有对象在其列表中具有相同的接口定义,这肯定是不对的 - 接口定义必须是唯一的。
在此示例中,为2个设备生成结构。其中一个定义了单个接口Gi1 / 1,但输出显示两个设备在interfaces
列表中具有相同的内容。
源代码如下:
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)
输出:
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
答案 0 :(得分:0)
接口成员属于类级别,而不是实例。
您需要将其更改为:
class PE(object):
def __init__(self, name):
self.name = name
self.interfaces = []
print('creating device',self.name)