我今天在课堂上有一个测验,我很惨地失败了,测验如下。有人可以帮我解释一下吗。
- 向 Link添加一个方法
open()
,将其从“左侧”的 Link 断开,从而打开项链,同时保持右侧的链条完好无损。例如,如果在 处抓住项链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()