0
class Element():
    def __init__(self, tag, childs = [], attributes = {}):
        self.childs = childs
        self.tag = tag
        self.attrib = attributes

    def get_childs(self):
        return self.childs

    def add_Child(self, child):
        self.childs.append(child)

class Html():
    def __init__(self):
        self.tag1 = Element("head")
        self.tag2 = Element("body")
        tag0 = Element("html", [self.tag1, self.tag2])

    def get_body(self):
        return self.tag2

    def get_head(self):
        return self.tag1

def main():
    html_object = Html()

   print html_object.get_body().get_childs()
   print html_object.get_head().get_childs()
   print "---------------"
   html_object.get_body().add_Child("new_child_added_to_body_ELEMENT")
   print "---------------"
   print html_object.get_body().get_childs()
   print html_object.get_head().get_childs()

if __name__ == "__main__":
   main()

when executing the above lines of code i get the following output:

[]
[]
---------------
---------------
['new_child_added_to_body_ELEMENT']
['new_child_added_to_body_ELEMENT']

while i wanted to insert the 'new_child_added_to_body_ELEMENT' only to the self.childs list of self.tag2 (the "body" Element"), what i end up getting is that the line is also added to the self.childs list of self.tag1 (the "head" Element) that is also declared inside of the Html class init.

there's obviously something about python classes that i'm missing so an explanation about what i'm doing wrong will be really appreciated.

harristyle
  • 178
  • 7
  • 2
    Also see [Mutable Default Arguments (& the Principle of “Least Astonishment”)](http://sopython.com/canon/49/mutable-default-arguments-the-principle-of-least-astonishment/) – PM 2Ring Oct 31 '16 at 13:59
  • thank you for referring me to the right place. just to see if i understood correctly: basically because the default list is created when the function is evaluated, and both of the instances use the default list, what happens is that both instances actually point to the same list? – harristyle Oct 31 '16 at 14:23
  • 1
    Yes. The default list arg of `childs` and the default dict arg of `attributes` are both created when the `__init__` function itself is created (when the code for the `Element` class is compiled), so all instances that get created share those defaults. BTW, in Python 2 you should be declaring your classes as new-style classes, eg `class Element(object):` otherwise you get old-style classes (in Python 3 all classes are new-style). See http://stackoverflow.com/questions/54867/what-is-the-difference-between-old-style-and-new-style-classes-in-python – PM 2Ring Oct 31 '16 at 14:29

0 Answers0