我制作了一个名为Protocol的对象,该对象带有一个端口和协议名称。然后将该对象存储在数组中。我的问题是如何访问数组中的对象?我主要是从事Java方面的工作,但我不太清楚。我不断收到错误的'int'对象没有属性getPort。
Protocol.py
对象/模型
class Protocol:
def __init__(self, protocolName, port):
self.protocolName = protocolName
self.port = port
def setPort(self, port):
self.port = port
def setProtocol(self,protocolName):
self.protocolName = protocolName
def getPort(self):
return self.port
def getProtocol(self):
return self.protocolName
JSONSlicer.py
函数在哪里
from Model.Protocol import Protocol
from Model.Service import Service
class JSONSlicers:
def protocolSeperator(self,protocols,num):
protocolsFound = [] # Protocol port # odds, Protocol name # evens
i=0
for p in protocols:
for sub in range(0,len(p.split('/')) - 1):
# protocol = Protocol(p.split('/')[sub])
fPort = p.split('/')[sub]
sub+=1
fProto = p.split('/')[sub]
#protocol = Protocol(p.split('/')[sub])
protocol = Protocol(fPort,fProto)
protocolsFound.append(protocol)
print(protocolsFound[0].getPort()) # Trying to print attribute of object here
return protocolsFound
答案 0 :(得分:3)
在Python中,您无需在使用变量之前声明变量。
该行:
protocolsFound = [num]
可能打算创建大小为num
的列表,但是您可以将其创建为空列表protocolsFound = []
并开始用.append()
填充,或者如果需要为了能够访问列表中的特定位置,您可以创建一个num
空位置(如protocolsFound = [None for _ in range(num)]
)的列表。不过,在编写良好的Python代码中很少需要这样做。
答案 1 :(得分:0)
这是错误的,因为您将protocolFound的第一个索引设置为 num
看看这条线是如何解决的,
protocolsFound = [num]
为什么在那里需要数字?