循环变量可见性/范围



我把头撞在桌子上,试图理解我做错了什么。

class Endpoint:
PortID = 0
MAC = ''
IP = ''
FQDN = ''
__init__()...

class Interface:
Index = 0
Endpoints = []
__init__()
...

IM主要部分我有:

for i in interfaces: #list of Interface objects
for e in endpoints: #list of Endpoint objects
is (some condidions):
i.Endpoints.append(e)
i.print() # prints all endpoints connected to the interface

然后在输出中,我有这样的东西:

ge0/0:
11:11:11:11:11:11
ge0/1:
11:11:11:11:11:11
22:22:22:22:22:22
ge0/2
11:11:11:11:11:11
22:22:22:22:22:22
33:33:33:33:33:33

我打算得到的是:

ge0/0:
11:11:11:11:11:11
ge0/1:
22:22:22:22:22:22
ge0/2
33:33:33:33:33:33

你明白了。这就像"i"变量不是在每次循环迭代中创建和销毁的,而只是更新。换句话说,它不是 Interface 对象的表示形式,而是整个循环的某种缓冲区组合。 我做错了什么?我怎样才能实现预期目标?

提前感谢您的帮助。

在你的主函数中:

for i in interfaces: #list of Interface objects
for e in endpoints: #list of Endpoint objects
is (some condidions):
i.Endpoints.append(e)
i.print() # prints all endpoints connected to the interface

您没有清除 i 的先前值

打印后添加i = 0(或任何语句以清除 i 的值(,如下所示:

for i in interfaces: #list of Interface objects
for e in endpoints: #list of Endpoint objects
is (some condidions):
i.Endpoints.append(e)
i.print() # prints all endpoints connected to the interface
i = 0

最新更新