我正在做一個項目,遇到了一個障礙。我不確定是否使不同類的對象相互引用,如果其中一個對象刪除了引用,則刪除該引用。
例如,我有一個網(wǎng)絡(luò)交換機(jī),交換機(jī)有端口。這些端口可能/可能沒有使用電纜連接到網(wǎng)絡(luò)上的其他交換機(jī)。請參考以下課程:
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
如果我創(chuàng)建了一個電纜對象并設(shè)置了左端口和右端口,它將引用這些端口。但當(dāng)它出現(xiàn)時,我希望端口對象也開始引用該電纜對象,反之亦然。此外,如果我從電纜中刪除了leftConnection,我希望這些更改也會返回到端口。有沒有一種方法可以做到這一點(diǎn),而不必手動添加對兩個對象的引用?
希望這個例子有幫助