Reputation: 79
I'm trying to implement a method for which is necessary to use recursion, but every time, I get the global name not defined
error
My class look like this:
class MyClass(object):
def _init_(self, name=None, content=None):
self.name = name
self.content = content
It's a node class, name it's just a text string and content a list of it's children (they are nodes too), is initialized as None
but the construction function that builds the tree give them a blank list if they have no children. The class works fine and so does the function but if I try to add recurtion to methods they just don't work, even if they work just fine as a standalone function, i.e.:
def get_nodes(self):
c = []
c.append(self.name)
if self.content != []:
for a in self.content:
c.extend(get_nodes(a))
return c
I know this is possible, what am I doing wrong?
Upvotes: 2
Views: 898
Reputation: 251448
You need to do a.get_nodes()
.
Also the initialization method is called __init__
, not _init_
(two underscores on both ends).
Edit: If you won't show your code, we can't tell you what's wrong with your code. This code works for me:
class MyClass(object):
def __init__(self, name=None, content=None):
self.name = name
self.content = content
def get_nodes(self):
c = []
c.append(self.name)
if self.content != []:
for a in self.content:
c.extend(a.get_nodes())
return c
>>> n = MyClass('me', [])
>>> m = MyClass('other', [n])
>>> m.get_nodes()
['other', 'me']
If your code doesn't work then you have to explain how your code is different from that.
Upvotes: 4