You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现不同类对象间的双向引用及引用自动同步?

解决方案:双向绑定自动同步实现

要实现Port和Cable的双向引用自动同步,核心是在一方修改引用时主动处理另一方的关联更新,同时清理旧连接关系。以下是修改后的实现代码:

修改后的Port类

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.__module = module  # 修复原拼写错误__modeule
        self._cable = cable  # 改为受保护属性,方便Cable类访问

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

    @property
    def cable(self):
        return self._cable

    @cable.setter
    def cable(self, new_cable):
        # 清理旧连接:如果当前Port已有Cable,断开该Cable对当前Port的引用
        if self._cable is not None:
            if self._cable._connectionLeft == self:
                self._cable._connectionLeft = None
            elif self._cable._connectionRight == self:
                self._cable._connectionRight = None
        # 设置新Cable
        self._cable = new_cable

修改后的Cable类

from port import Port

class Cable(object):
    cableNumber = 1

    def __init__(self, connLeft=None, connRight=None):
        self._connectionLeft = None
        self._connectionRight = None
        self.__cableId = Cable.cableNumber
        Cable.cableNumber += 1
        # 初始化时自动绑定端口
        if connLeft is not None:
            self.setLeft(connLeft)
        if connRight is not None:
            self.setRight(connRight)

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

    def setLeft(self, connLeft):
        if not isinstance(connLeft, Port):
            connLeft = None
        
        # 清理旧左端口的Cable引用
        if self._connectionLeft is not None:
            self._connectionLeft.cable = None
        
        # 设置新左端口,并同步更新该Port的Cable引用
        self._connectionLeft = connLeft
        if connLeft is not None:
            connLeft.cable = self

    def setRight(self, connRight):
        if not isinstance(connRight, Port):
            connRight = None
        
        # 清理旧右端口的Cable引用
        if self._connectionRight is not None:
            self._connectionRight.cable = None
        
        # 设置新右端口,并同步更新该Port的Cable引用
        self._connectionRight = connRight
        if connRight is not None:
            connRight.cable = self

关键实现说明

  • 属性访问调整:将双方的私有属性改为受保护(单下划线),同时给Port的cable添加property装饰器,方便在设置时自动处理旧连接的清理。
  • 双向同步逻辑:
    • 当Cable调用setLeft/setRight时,先清理旧端口的Cable引用,再设置新端口,并让新端口的cable指向当前Cable。
    • 当Port通过cable setter设置新Cable时,先清理旧Cable对当前Port的引用,再绑定新Cable。
  • 初始化自动绑定:Cable的__init__方法中加入初始化时的自动绑定逻辑,创建Cable时传入端口即可完成双向关联。
  • 修复原代码bug:修正了Cable类setRight方法中错误的判断条件(原代码误用connLeft进行类型检查)。

使用示例

# 创建两个Port实例
port1 = Port('Gi', 'SwitchA', '1', '0')
port2 = Port('Gi', 'SwitchB', '2', '0')

# 创建Cable并绑定端口,自动完成双向引用
cable = Cable(port1, port2)
print(port1.cable)  # 输出: Gi 0/1  <----(1)---->  Gi 0/2
print(cable)        # 输出: Gi 0/1  <----(1)---->  Gi 0/2

# 断开Cable的左端口
cable.setLeft(None)
print(port1.cable)  # 输出: None
print(cable)        # 输出: None  <----(1)---->  Gi 0/2

# 重新绑定左端口到新的port3
port3 = Port('Fa', 'SwitchC', '3', '1')
cable.setLeft(port3)
print(port3.cable)  # 输出: Fa 1/3  <----(1)---->  Gi 0/2
print(cable)        # 输出: Fa 1/3  <----(1)---->  Gi 0/2

内容的提问来源于stack exchange,提问作者Anmol Brar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 01:15:04