我遇到python问题我写这个类
class TNode(object):
def __init__(self, name):
self.name=name
self._children=[]
def add(self, c):
self._children=self._children +[c]
def children(self):
t=[]
for f in self._children:
t+=f
return t
def height(self):
h = 1
for node in self._children:
h = max(h, node.height() + 1)
return h
def count(self):
cnt = 1
for node in self._children:
cnt += node.count()
return cnt
def count_by_name(self, name):
cbn=0
for node in self._children:
cbn+=node.count(name)
return cbn
def paths(self, name):
pset = set()
if self.name == name:
pset.add((name,))
for node in self._children:
for p in node.path(name):
pset.add((self.name,)+p)
return pset
和写入功能后:
def create_tree(d):
root=TNode(d['name'])
for node in (d['children']):
if len(d['children'])!=0:
child=TNode(node['name'])
tree=root.add(child)
create_tree(node)
return tree
这是字典:
d = {'name':'musica', 'children':
[{'name':'rock', 'children':
[{'name':'origini','children':[]},
{'name':'rock&roll','children':[]},
{'name':'hard rock', 'children':[]}]},
{'name':'jazz', 'children':
[{'name':'origini', 'children':
[{'name':'1900', 'children':
[{'name':'origini','children':[]}]}]},
{'name':'ragtime', 'children':[]},
{'name':'swing', 'children':[]}]}]}
我尝试做一些操作,如:tree.count(),tree.paths()或tree.height(),但我有相同的响应'NoneType' object has no attribute 'count/paths...'
我希望你能帮助我:)。
答案 0 :(得分:4)
我认为你的设计有问题。
根据您的代码,tree
不是TNode
个实例:
def create_tree(d):
root=TNode(d['name'])
for node in (d['children']):
if len(d['children'])!=0:
child=TNode(node['name'])
tree=root.add(child)
create_tree(node)
return tree
tree
是方法add()
的返回值,即None
。
您可以在count()
上呼叫paths()
或root
,但不能在tree
上呼叫。
也许您想要返回root
而不是tree
?