我今天在课堂上有一个测验,我失败了,它的测验是低于。 有人可以帮我解释一下。蟒蛇 - 努力设计这
- 添加的方法
open()
到链接,将链接断开它只是在它的左边“,从而打开了项链,同时保持链完整的权利。例如,如果在link1
处抓住项链,则拨打link1.open()
将断开link3
与link1
的连接,但将一个链条从link1
连接到link3
。
这是我目前有:
class Diamond(object):
def __str__(self):
return "Diamond"
class Ruby(object):
def __str__(self):
return "Ruby"
class Visitor:
def __str__(self):
return self.__class__.__name__
class Link(object):
def __init__(self, index, jewel = None):
self.jewel = jewel
self.index = index
def connectTo(self, link):
self.nextLink = link
def __next__(self):
return self.nextLink or None
def attach(self, jewel):
if not self.jewel:
self.jewel = jewel
def detatch(self):
stone = self.jewel
self.jewel = None
return stone
def open(self):
pass
def __str__(self):
return "link%d" % (self.index)
class Necklace(object):
def __init__(self, base):
self.base = base
def describe(self):
link = self.base
while True:
print link, "with", link.jewel, "attatched to", link.nextLink, "with", link.nextLink.jewel
link = link.nextLink
if link == self.base:
break
def getJewel(self):
link = self.base
while True:
link = link
if isinstance(link.jewel, Diamond):
print "a", link.detatch()
break
link = link.nextLink
if link == self.base:
print "nothing..."
break
def acceptVisitor(self, visitor):
visitor.visit(self)
class DiamondThief(object, Visitor):
def __init__(self, base):
self.base = base
self.jewel = self.base.jewel
def visit(self, necklace):
necklace.getJewel()
def searchForDiamond(self):
self.visit(myNecklace)
link1 = Link(1, Ruby())
link2 = Link(2, Diamond())
link3 = Link(3, Ruby())
link1.connectTo(link2)
link2.connectTo(link3)
link3.connectTo(link1)
myNecklace = Necklace(link1)
myNecklace.describe()
print "Uh on here comes a thief..."
thief = DiamondThief(link1)
print "Oh no he took "
thief.searchForDiamond()
myNecklace.describe()
你说的意思是“这个给我解释”? – pradyunsg 2013-03-08 07:49:25
我不知道如何做到这一点,就像我得到了什么被问到,但我不能为我的生活设计它,而我现在正在尝试自己做,以了解它,但我根本找不到它。像什么类和功能看起来像 – user1758231 2013-03-08 07:51:44
@ user1758231在目前的形式,你的问题太广泛。我怀疑如果我们其中一个公布此解决方案,您不会学习设计类似的问题。您至少可以通过编写类的签名和它们之间的交互来了解您的问题。 – sidi 2013-03-08 07:58:01