代码如下,
问题出在toString方法,假如对象A有childTags,然后调用toString时候就循环调用childTags的每个对象的toString方法,但是我Debug看到传给toString方法的self对象一直看起来都是最初的A对象,请问代码该怎么写,问题出在哪里,初学python,谢谢了。
class Tag(object):
attributes = {}
html = ''
childTags = []
'''__init(self,name, attributes, HTML)'''
def __init__(self, name, *args):
self.name = name
if len(args) < 1 :
return
if len(args) == 1 and isinstance(args[0], dict) :
self.attributes = args[0]
return
elif len(args) == 1 and isinstance(args[0], str):
self.html = args[0]
return
if len(args) == 2:
if isinstance(args[0], dict) and isinstance(args[1], str):
self.attributes = args[0]
self.html = args[1]
elif isinstance(args[1], dict) and isinstance(args[0], str):
self.attributes = args[1]
self.html = args[0]
return
else:
raise Exception, 'Illegal arguments'
def toString(self):
if len(self.childTags) == 0:
tmp = ' '
for attribute in self.attributes.keys():
tmp = tmp + attribute + '=\'' + self.attributes[attribute] + '\' '
tag = '' + self.html + '' + self.name + '>'
else:
tmpAttr = ' '
tmpChildren = ''
for child in self.childTags:
tmpChildren = tmpChildren + child.toString() + '\n'
for attribute in self.attributes.keys():
tmpAttr = tmpAttr + attribute + '=\'' + self.attributes[attribute] + '\' '
tag = '' + self.html + tmpChildren + '' + self.name + '>'
return tag
def __str__(self):
return self.toString()
def setINNERHTML(self, html):
if html == '':
self.html = ''
else:
self.html = html
def setAttributes(self, attributes):
if isinstance(attributes, dict):
self.attributes = attributes
else:
raise Exception, 'Attributes of tag must be a dictionary'
def contains(self, *childTags):
for tag in childTags:
if isinstance(tag, Tag):
self.childTags.append(tag)
else:
pass