Python 2.7: strange constructor behavior: changing wrong field -



Python 2.7: strange constructor behavior: changing wrong field -

in code:

# coding=utf-8 def print_tree(node, tree=0): print(u"|---" * tree + u"-> %s" % node) kid in node.children: print_tree(kid, tree + 1) class person(object): parent = none first_name = none last_name = none children = [] def __str__(self): homecoming '%s %s' % (self.first_name, self.last_name) def __unicode__(self): homecoming u'%s %s' % (self.first_name, self.last_name) def __init__(self, first_name, last_name, parent=none): if parent not none: if not isinstance(parent, person): raise attributeerror('`parent` not `person` type!') self.parent = parent self.parent.children.append(self) self.first_name = first_name self.last_name = last_name #self.children = [] root = person('alan', 'smith') p1 = person('barbara', 'smith', root) p2 = person('basia', 'smith', root) p3 = person('bary', 'smith', root) print_tree(root)

if remove comment #self.children = [] illustration works fine. don't understand why must add together line ?

in debugger discovered line self.parent.children.append(self) adds self self.children

why ?

in python, when declare attribute @ class level, makes class attribute (shared between instances of class). in case, want instance attributes. instance attributes must created in constructor (your self.children = []).

python python-2.7

Comments

Popular posts from this blog

web services - java.lang.NoClassDefFoundError: Could not initialize class net.sf.cglib.proxy.Enhancer -

Accessing MATLAB's unicode strings from C -

javascript - mongodb won't find my schema method in nested container -