本问题已经有最佳答案,请猛点这里访问。
我从Python开始,并努力用类对象填充字典。我的目标是用设备定义填充dictionary并为所有设备创建接口。问题是当我试图用接口类对象填充内部列表时,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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) |
输出:
1 2 3 4 5 6 7 | 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 |
接口成员属于类级,而不是实例级。
你需要把它改成:
1 2 3 4 5 | class PE(object): def __init__(self, name): self.name = name self.interfaces = [] print('creating device',self.name) |