Python组成:盒子中的弹珠

时间:2014-04-17 20:00:16

标签: python instantiation composition

这是一个处理多种构图的玩具问题:

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

在Python中实现多个'has-a'组合的最佳模式是什么? (我发现单个有一个例子,但没有偶然发现多个组合示例)。

我的第一个猜测,无论它值多少,都是通过Box类中包含的方法处理Marble对象(例如create_marble,pass_marble,delete_marble方法),并在Box类中维护一个Marbles列表作为属性。但这真的是最好的方法吗?

2 个答案:

答案 0 :(得分:1)

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)

答案 1 :(得分:0)

是的,composition表示所有者对象(Box)负责创建和销毁拥有的对象(Marble)。