我正在编写一个应用程序,其中标签是可链接的,并且需要检索整个链接标签链.不允许自我引用.运行以下代码最终会得到一些非常奇怪的结果:
class Tag(object): def __init__(self,name): self.name = name self.links = [] def __repr__(self): return "<Tag {0}>".format(self.name) def link(self,tag): self.links.append(tag) def tag_chain(tag,kNown=[]): chain = [] if tag not in kNown: kNown.append(tag) print "KNown: {0}".format(kNown) for link in tag.links: if link in kNown: continue else: kNown.append(link) chain.append(link) chain.extend(tag_chain(link,kNown)) return chain a = Tag("a") b = Tag("b") c = Tag("c") a.link(b) b.link(c) c.link(a) o = tag_chain(a) print "Result:",o print "------------------" o = tag_chain(a) print "Result:",o
结果:
KNown: [<Tag a>] KNown: [<Tag a>,<Tag b>] KNown: [<Tag a>,<Tag b>,<Tag c>] Result: [<Tag b>,<Tag c>] ------------------ KNown: [<Tag a>,<Tag c>] Result: []
所以,不知何故,我不小心创建了一个闭包.据我所见,已知应该已经超出范围并在函数调用完成后消失.
如果我将chain_tags()的定义更改为未设置默认值,则问题就会消失:
... def tag_chain(tag,kNown): ... o = tag_chain(a,[]) print "Result:",o print "------------------" o = tag_chain(a,o
为什么是这样?