How can I make two objects from different classes to reference each other?

Question:

I am working on a project and have encountered a roadblock. I’m not sure to make objects of different classes reference each other and delete the reference if one of them drops it.

For example, I have a network switch and the switch has ports. Those ports may/may not be connecting to other switches on the network using a cable. Please refer to the classes below:

Port object:

class Port(object):
linkSpeeds = {'Fa' : 'Fast',
              'Gi' : 'Gigabit',
              'Te' : 'TenGigabit',
              'Fo' : 'FortyGigabit'}

def __init__(self, linkSpeed, brick, port, module=None, cable=None):
    self.__linkSpeed = self.linkSpeeds[linkSpeed]
    self.__brick = brick
    self.__port = port
    self.__modeule = module
    self.__cable = cable

def __repr__(self):
    outputString = '{} {}/{}/{}'
    return outputString.format(self.__linkSpeed[:2], self.__brick, self.__modeule, self.__port)

def connect(self, cableId):
    self.__cable = cableId

Cable Object:

from port import Port

class Cable(object):

cableNumber = 1

def __init__(self, connLeft = None, connRight = None):
    self.__connectionLeft = connLeft if isinstance(connLeft, Port) else None
    self.__connectionRight = connRight if isinstance(connRight, Port) else None
    self.__cableId = Cable.cableNumber
    Cable.cableNumber += 1

def __repr__(self):
    outputString = '{}  <----({})---->  {}'
    return outputString.format(self.__connectionLeft, self.__cableId, self.__connectionRight)

def setLeft(self, connLeft):
    self.__connectionLeft = connLeft if isinstance(connLeft, Port) else None

def setRight(self, connRight):
    self.__connectionRight = connRight if isinstance(connRight, Port) else None

If I create a cable object and set the left and right port it references those ports. But when it does I want the port object to also start referencing that cable object and vice versa. Also, if I delete the leftConnection from the cable, I want those changes to reciprocate to the port as well. Is there a way to do that without manually having to add references to both objects?

Asked By: Anmol Brar

||

Answers:

Hope this example is helpful

class Port(object):
    linkSpeeds = {'Fa': 'Fast',
                  'Gi': 'Gigabit',
                  'Te': 'TenGigabit',
                  'Fo': 'FortyGigabit'}

    def __init__(self, linkSpeed, brick, port, module=None, cable=None):
        self.__linkSpeed = self.linkSpeeds[linkSpeed]
        self.__brick = brick
        self.__port = port
        self.__modeule = module
        self._cable = cable

    def __repr__(self):
        outputString = '{}{}/{}/{}'.format(self.__linkSpeed[:2], self.__brick, self.__modeule, self.__port)
        if self._cable:
            outputString = "{}-cable{}".format(outputString, self._cable)
        return outputString

    def connect(self, cableId):
        self._cable = cableId


class Cable(object):
    cableNumber = 1

    def __init__(self, connLeft=None, connRight=None):
        self.__connectionLeft = connLeft if isinstance(connLeft, Port) else None
        self.__connectionRight = connRight if isinstance(connRight, Port) else None
        self.__cableId = Cable.cableNumber
        Cable.cableNumber += 1

    def __repr__(self):
        outputString = '{}  <----({})---->  {}'
        return outputString.format(self.__connectionLeft, self.__cableId, self.__connectionRight)

    @property
    def left(self):
        return self.__connectionLeft

    @left.setter
    def left(self, port):
        """Join cable with port and port with cable"""
        self.__connectionLeft = None
        if isinstance(port, Port):
            self.__connectionLeft = port
            port._cable = self.__cableId

    @property
    def right(self):
        return self.__connectionRight

    @right.setter
    def right(self, port):
        """Join cable with port and port with cable"""
        self.__connectionRight = None
        if isinstance(port, Port):
            self.__connectionRight = port
            setattr(port, "_cable", self.__cableId)


# init ports and cable
port1 = Port(linkSpeed="Fa", brick="1", port="1", module="1")
port2 = Port(linkSpeed="Fa", brick="2", port="2", module="2")
cable = Cable()
print(port1)  # Fa1/1/1
print(cable)  # None  <----(1)---->  None
print(port2)  # Fa2/2/2
print()

# connect ports with cable
cable.left = port1
cable.right = port2
print(port1)  # Fa1/1/1-cable1
print(cable)  # Fa1/1/1-cable1  <----(1)---->  Fa2/2/2-cable1
print(port2)  # Fa2/2/2-cable1
Answered By: pyjedy
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.