[英]How to access object from array of objects in Python
I have made a object called Protocol that takes in a port and protocol name.我创建了一个名为 Protocol 的对象,它接受端口和协议名称。 This object is then stored in an array.
然后将该对象存储在一个数组中。 My question is how do i access my object in the array?
我的问题是如何访问数组中的对象? Im coming from mostly doing Java and I can't quite figure it out.
我主要是做 Java 的,我不太明白。 I keep getting error 'int' object has no attribute getPort.
我不断收到错误“int”对象没有属性 getPort。
Protocol.py
Object/Model 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
Where function is 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
In Python, you don't have to declare a variable before using it.在 Python 中,您不必在使用变量之前声明它。
The line:线路:
protocolsFound = [num]
Is probably intended to create a list of size num
, but you can either just create it as an empty list protocolsFound = []
and start filling it with .append()
, or if you need to be able to access specific positions in the list, you can create a list with num
empty positions like protocolsFound = [None for _ in range(num)]
.可能打算创建一个大小为
num
的列表,但您可以将其创建为空列表protocolsFound = []
并开始使用.append()
填充它,或者如果您需要能够访问列表中的特定位置,您可以创建一个包含num
空位置的列表,例如protocolsFound = [None for _ in range(num)]
。 This is rarely needed in well-written Python code, though.但是,在编写良好的 Python 代码中很少需要这样做。
It errors because you set the first index of protocolsFound to an in num它出错是因为您将 protocolFound 的第一个索引设置为 in num
Take a look at this line an fix it,看看这条线修复它,
protocolsFound = [num]
why do you need the num in there?为什么你需要那里的号码?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.