【问题标题】:Using a list as a class parameter使用列表作为类参数
【发布时间】:2019-11-20 13:44:23
【问题描述】:
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 保持为空。

【问题讨论】:

  • 旁注:真的有必要拥有numHops吗?它不应该总是等于len(hops)吗?
  • 如果数据包只通过交换机,它不会被记录为一跳(数据包的ttl值不会减少),因此len(hops)将为零,但numHops值将保持为1

标签: python list class oop


【解决方案1】:

您将列表传递给__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

【讨论】:

  • 也许你想复制hops 这样的self.hops = hops.copy() 以防止一些不受欢迎的行为?
猜你喜欢
  • 2020-10-07
  • 1970-01-01
  • 1970-01-01
  • 2011-06-26
  • 1970-01-01
  • 1970-01-01
  • 2014-05-03
  • 2018-03-20
  • 2021-04-24
相关资源
最近更新 更多