Python作品:盒子里的弹珠

2024-04-24 16:44:36 发布

您现在位置:Python中文网/ 问答频道 /正文

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

有两个对象类,分别表示大理石和长方体。大理石总是包含在长方体中,长方体有一个类方法来表示当前在其中的大理石。一个大理石,一旦实例化,应该能够被传递到任何其他现有的框(甚至可能是另一个扩展对象)。你知道吗

在Python中实现多个has-a组合的最佳模式是什么?(我找到了单篇has-a的例子,但没有偶然发现多篇作文的例子)。你知道吗

我的第一个猜测,不管它值多少钱,都是通过Box类中包含的方法(例如create\u Marble、pass\u Marble、delete\u Marble方法)来处理大理石对象,并在Box类中维护一个大理石列表作为属性。但这真的是最好的方法吗?你知道吗


Tags: 对象实例方法boxcreate模式passdelete
2条回答
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)

是的,composition意味着所有者对象(Box)负责创建和销毁所有者对象(Marble)。你知道吗

相关问题 更多 >