Skip to main content
 首页 » 编程设计

python之如何实现对象属性的两个方向

2025年05月04日11telwanggs

如果我将一个对象分配给另一个对象的属性,那么在给定第二个对象的情况下还获得第一个对象的自然方法是什么?我认为这有点像外键在数据库中的作用。

class Box(object): 
    things = [] 
 
class Thing(object): 
    box = None 
 
thing = Thing() 
box = Box() 
 
# thing.box updates the box.things 
thing.box = box 
thing in box.things # should be true 
 
# box.things updates thing.box 
box.things.append(thing) 
thing.box == box # should be true 

我还想通过一对一和多对多关系来实现这一点。这可能吗?

我目前一直在保存所有“东西”的全局集合,然后在“盒子”上提供一个属性,让什么属于什么的信息只在一个地方。然而,事物的集合是如此庞大,我想将指向“事物”对象的指针放在“盒子”对象本身中。

请您参考如下方法:

对于“事物”的情况,如果您只想跟踪一个对象, Python 的属性开箱即用。

至于许多“事物”的容器,单个属性不会 work - 因为你想跟踪指向对象属性的容器的变化 (属性适用于对属性本身的更改)。因此,一个小的自定义容器类可以对添加到容器中的对象进行所需的更改,这是一种简单的方法。 (我认为“集合”比列表更适合您)

class Thing(object): 
    def get_box(self): 
        return self._box 
    def set_box(self, box): 
        self._box = box 
        if not self in box.things: 
            box.things.add(self) 
    box = property(get_box, set_box) 
 
class CallbackSet(set): 
    def __new__(cls, box, *args, **kw): 
        self = set.__new__(cls, *args, **kw) 
        self.box = box 
    def add(self, item): 
        item.box = self.box 
        return set.add(self, item) 
 
class Box(object): 
    def __init__(self): 
        self.things = CallbackSet(self)