class Item:
def __init__(self, box, description):
self._box = box
self._description = description
class Box:
def __init__(self):
self.item_1 = Item(self, 'A picture')
self.item_2 = Item(self, 'A pencil')
#etc
old_stuff = Box()
print(old_stuff.item_1.box.item_1.box.item_2.box.item_1)
上面显示了一个示例代码示例,它比纯文本更好地证明了我的问题。有没有更好的方法可以在哪个盒子里找到东西?(图片是什么盒子?(由于我不特别喜欢上述解决方案,因为它允许这种奇怪的上下呼叫可以永远发生。有没有更好的方法来解决此问题,或者这只是一个案例:如果它很愚蠢并且有效,那就不是愚蠢的。
注意:此技巧不是特定于Python的。在所有面向对象的编程laguages中都是可行的。
没有正确或错误的方法来执行此操作。解决方案取决于您要如何使用对象。
如果您的用例要求将项目知道存储在哪个盒子中,则需要对盒子进行引用;如果不是,那么您就不需要协会。
同样,如果您需要在给定框中的哪个项目,则需要引用框对象中的项目。
即时要求(即当前上下文(总是决定一个人如何设计类模型。例如,一个人在UI层中对项目或盒子进行建模与在服务层中建模的方式不同。
您必须介绍新类 - 项目管理器或简单或其他外部结构,以存储有关哪个框包含的信息:
class Item:
def __init__(self, description):
self.description = description
class Box:
def __init__(self, item_1, item_2):
self.item_1 = item_1
self.item_2 = item_2
class ItemManager:
def __init__(self):
self.item_boxes = {}
def register_item(self, item, box):
self.item_boxes[item] = box
def deregister_item(self, item):
del self.item_boxes[item]
def get_box(self, item):
return self.item_boxes.get(item, None)
item_manager = ItemManager()
item_1 = Item("A picture")
item_2 = Item("A pencil")
item_3 = Item("A teapot")
old_stuff = Box(item_1, item_2)
item_manager.register_item(item_1, old_stuff)
item_manager.register_item(item_2, old_stuff)
new_stuff = Box(item_3, None)
item_manager.register_item(item_3, new_stuff)
box_with_picture = item_manager.get_box(item_2)
print box_with_picture.item_1.description
还请参见SRP:一个项目不知道哪个框包含它。