0

This code is meant to create a graph implementation. However, all of the nodes "self.children" link to the same list in memory, so adding children to any of them adds it to all of them. I can not for the life of me think of why this would happen, I have made classes like this many times, and not had such an issue.

I mean, just because you define a list in the default values doesn't mean I make a list then and there, does it? This is confusing...

class DescisionNode(object):
    def __init__(self,data,score,childs=[]):
        self.data = data
        self.score = score
        self.parent = None
        self.children = childs
    def getTop(self):
        if self.parent == None:
            return self
        else:
            return self.parent.getTop()
    def getEnds(self):
        out = []
        if len(self.children)==0:
            return [self]
        else:
            print(self,self.children)
            for n in self.children:
                out += n.getEnds()
            return out
    def add(self, newNode):
        if newNode.parent == None:
            newNode.parent = self
        else:
            raise Exception("Parent already exists.")
        if newNode is self:
            raise Exception("self may not be child")
        self.children.append(newNode)
Ryan
  • 451
  • 4
  • 11

1 Answers1

-1

This is due to this: http://docs.python-guide.org/en/latest/writing/gotchas/#mutable-default-arguments

Python’s default arguments are evaluated once when the function is defined, not each time the function is called (like it is in say, Ruby). This means that if you use a mutable default argument and mutate it, you will and have mutated that object for all future calls to the function as well.

You can find some discussion here: "Least Astonishment" and the Mutable Default Argument

It comes simply from the fact that functions in Python are first-class objects, and not only a piece of code. As soon as you get to think into this way, then it completely makes sense: a function is an object being evaluated on its definition; default parameters are kind of "member data" and therefore their state may change from one call to the other - exactly as in any other obje

Community
  • 1
  • 1
Davis Yoshida
  • 1,757
  • 1
  • 10
  • 24
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/11124740) – ρяσѕρєя K Feb 03 '16 at 05:24
  • Edited with excerpts. Thank you. – Davis Yoshida Feb 03 '16 at 05:57