1

i've a problem with python i write this Class

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 

and after write function:

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 

this is the dictionary:

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':[]}]}]} 

i try to do some operation like: tree.count(), tree.paths() or tree.height() but i have ever the same response 'NoneType' object has no attribute 'count/paths...'

i hope you can help me :)

1
  • 2
    It means tree is equal to None. Look at how you defined tree. Commented Nov 24, 2015 at 16:12

1 Answer 1

4

I think there's something wrong with your design.

According to your code, tree is not a TNode instance:

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 is the return value of method add(), which is None.

You can call count() or paths() on root, but not on tree.

Maybe you want to return root instead of tree?

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.