Re: Recursive function returning a list
- From: Steve Holden <steve@xxxxxxxxxxxxx>
- Date: Mon, 17 Jul 2006 18:43:34 +0100
Fabian Steiner wrote:
Hello!
I have got a Python "Device" Object which has got a attribute (list) called children which my contain several other "Device" objects. I implemented it this way in order to achieve a kind of parent/child relationship.
Now I would like to get all children of a given "Device" object and thought that it would be the best way to use recursive function.
This is what I got so far:
def getAllChildren(self, children=[]):
if self.children:
children.extend(self.children)
for child in self.children:
child.getAllChildren(children)
return children
Unfortunately, it doesn't work like expected since the default parameter children=[] is evaluated only once. That's why the children list becomes larger and larger after calling the method several times but I can't think of another possibility.
Do you have any ideas?
This is a standard question, and has a standard answer: replace
def getAllChildren(self, children=[]):
with
def getAllChildren(self, children=None):
if children is None:
children = []
That way a new empty list is created for each call that receives no "children" argument. Otherwise the same (once-empty) list is used for them all.
regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden
.
- References:
- Recursive function returning a list
- From: Fabian Steiner
- Recursive function returning a list
- Prev by Date: Re: Augument assignment versus regular assignment
- Next by Date: Re: pyKML: where to get it?
- Previous by thread: Recursive function returning a list
- Next by thread: Re: Recursive function returning a list
- Index(es):
Relevant Pages
|