使用列表作为类参数

时间:2019-11-20 13:44:23

标签: python list class oop

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值被更新,跳数保持为空。

1 个答案:

答案 0 :(得分:6)

您将列表传递到__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
相关问题