【问题标题】:Python composition: marbles in a box蟒蛇组成:盒子里的弹珠
【发布时间】:2014-04-18 04:13:38
【问题描述】:

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

有两个对象类,代表弹珠和盒子。 Marble 总是包含在 Box 中,并且 Box 有一个类方法来表示当前在其中的弹珠。 Marble 一旦被实例化,就应该能够被传递给任何其他现有的 Box(或者甚至可能是另一个可扩展的对象)。

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

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

【问题讨论】:

  • “但这真的是最好的方法吗?”是的。
  • 好的。那么 Box 应该有一个传递大理石处理方法的超类吗? (这样如果我定义其他包含对象,例如 Bin,我就可以保持干燥......)
  • 保持模糊。 class MarbleContainingObject :)

标签: python instantiation composition


【解决方案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)

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2010-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-06
      • 2017-02-23
      • 1970-01-01
      • 2010-10-27
      相关资源
      最近更新 更多