Python合成:盒子里的弹珠

Python合成:盒子里的弹珠,python,instantiation,composition,Python,Instantiation,Composition,这里有一个处理多重合成的玩具问题: 有两个对象类,分别表示大理石和长方体。大理石始终包含在长方体中,长方体有一个类方法来表示当前在其中的大理石。大理石一旦实例化,就应该能够传递给任何其他现有的盒子(或者甚至是另一个可扩展的对象) 在Python中实现多个“has-a”组合的最佳模式是什么?(我找到了单一的has-a示例,但没有偶然发现一个多重合成示例) 我的第一个猜测是,不管它值多少钱,都是通过Box类中包含的方法(例如创建、传递、删除大理石方法)来处理大理石对象,并在Box类中维护大理石列表作

这里有一个处理多重合成的玩具问题:

有两个对象类,分别表示大理石和长方体。大理石始终包含在长方体中,长方体有一个类方法来表示当前在其中的大理石。大理石一旦实例化,就应该能够传递给任何其他现有的盒子(或者甚至是另一个可扩展的对象)

在Python中实现多个“has-a”组合的最佳模式是什么?(我找到了单一的has-a示例,但没有偶然发现一个多重合成示例)


我的第一个猜测是,不管它值多少钱,都是通过Box类中包含的方法(例如创建、传递、删除大理石方法)来处理大理石对象,并在Box类中维护大理石列表作为属性。但这真的是最好的方法吗?

是的,这意味着所有者对象(长方体)负责创建和销毁所有者对象(大理石)。

“但这真的是最好的方法吗?”是的。好的。所以Box应该有一个超级类来传递大理石处理方法?(这样,如果我定义了其他包含对象,例如,可能是一个垃圾箱,我就可以保持东西干燥…)保持它的模糊性<代码>类MarbleContainingObject:)
class Marble(object):
    def __init__(self,color=None):
        self.color=color # I'm assuming this is necessary,
                         # just because "colored marbles in
                         # a box" is so typical
    def __repr__(self):
        return "Marble({})".format(self.color)

class Box(object):
    def __init__(self,name=None,marbles=None):
        self.name = name
        if marbles is None:
            marbles = list()
        self.marbles = marbles
    def addMarble(self,color=None):
        self.marbles.append(Marble(color))
    def giveMarble(self,other):
        # import random
        index = random.randint(0,len(self.marbles)-1)
        try:
            other.marbles.append(self.marbles.pop(index))
        except AttributeError:
            raise NotImplementedError("Can't currently pass marbles to an "
                                      "object without a marbles list")
    def __str__(self):
        return '\n'.join([str(marble) for marble in self.marbles])

a = Box()
b = Box()
for _ in range(10): a.addMarble()
print(a)
# Marble(None)
# Marble(None)
# Marble(None)
# Marble(None)
# Marble(None)
# Marble(None)
# Marble(None)
# Marble(None)
# Marble(None)
# Marble(None)
a.giveMarble(b)
print(b)
# Marble(None)