这是一个处理多重组合的玩具问题:
有两个对象类,代表弹珠和盒子。 Marble 总是包含在 Box 中,并且 Box 有一个类方法来表示当前在其中的弹珠。 Marble 一旦实例化,就应该能够传递给任何其他现有的 Box(或者甚至可能是另一个对象以实现可扩展性)。
在 Python 中实现多个“has-a”组合的最佳模式是什么? (我发现了单个 has-a 示例,但没有偶然发现多个组合示例)。
我的第一个猜测,无论其值(value)如何,都是通过 Box 类中包含的方法(例如 create_marble、pass_marble、delete_marble 方法)处理 Marble 对象,并将 Marbles 列表作为 Box 类中的一个属性进行维护。但这真的是最好的方法吗?
请您参考如下方法:
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)
