Skip to main content
 首页 » 编程设计

python之使用列表作为类参数

2025年05月04日13lexus

class Interface(): 
    def __init__(self, localIP, remoteIP, numHops, hops): 
        self.localIP = localIP 
        self.remoteIP = remoteIP 
        self.numHops = numHops 
        self.hops = [] 

我想创建一个这样的实例:

hops, hopIps = stripRoute(ssh.run("traceroute -I " + str(dstHost.ip), hide=True)) 
host.interfaces.append(Interface(host.ip, dstHost.ip, hops, hopIps)) 
print(hops) 
print(hopIps) 

从打印语句中我可以看到 hopIps 的值和长度为 1,这是预期的。然而,当我查询接口(interface)的新实例时,只有 numHops 值被更新,hops 仍然是空的。

请您参考如下方法:

你将一个列表传递给 __init__ 但从未使用过它

class Interface(): 
    def __init__(self, localIP, remoteIP, numHops, hops): 
        self.localIP = localIP 
        self.remoteIP = remoteIP 
        self.numHops = numHops 
        self.hops = [] 

只需将您的列表分配给成员

class Interface(): 
    def __init__(self, localIP, remoteIP, numHops, hops): 
        self.localIP = localIP 
        self.remoteIP = remoteIP 
        self.numHops = numHops 
        self.hops = hops