[英]How to access object from array of objects in Python
我創建了一個名為 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
在 Python 中,您不必在使用變量之前聲明它。
線路:
protocolsFound = [num]
可能打算創建一個大小為num
的列表,但您可以將其創建為空列表protocolsFound = []
並開始使用.append()
填充它,或者如果您需要能夠訪問列表中的特定位置,您可以創建一個包含num
空位置的列表,例如protocolsFound = [None for _ in range(num)]
。 但是,在編寫良好的 Python 代碼中很少需要這樣做。
它出錯是因為您將 protocolFound 的第一個索引設置為 in num
看看這條線修復它,
protocolsFound = [num]
為什么你需要那里的號碼?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.