0

I have made a object called Protocol that takes in a port and protocol name. 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. I keep getting error 'int' object has no attribute getPort.

Protocol.py Object/Model

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

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
2
  • protocolsFound = [num] puts a number in the array, instead of a protocol. This gives you the error when you're trying to call getPort on this number Commented Feb 17, 2020 at 3:22
  • Please share the entire error message. Also, variable and function names should follow the lower_case_with_underscores style (see PEP 8). Commented Feb 17, 2020 at 3:59

2 Answers 2

3

In Python, you don't have to declare a variable before using it.

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)]. This is rarely needed in well-written Python code, though.

Sign up to request clarification or add additional context in comments.

Comments

0

It errors because you set the first index of protocolsFound to an in num
Take a look at this line an fix it,

protocolsFound = [num]

why do you need the num in there?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.