(original) (raw)
#!/usr/bin/env python2.7 import random ##################################### # Set APPLY_FIX to False to see the broken code # Set APPLY_FIX to True to see the fix ##################################### APPLY_FIX = True # our test object, whilst can also hold children class Obj: id = None children = [] def __init__(self): if APPLY_FIX: self.children = [] def add_child(self, i): print "appending child %s to %s" % ( i, self ) self.children.append(i) # our test ids ids = xrange(0, 10) # this creates our new object def CreateObj(): new_obj = Obj() print "CreateObj() called, new instance created: %s" % ( new_obj ) return new_obj # create a list of objects, based on the test ids _objs = [] for x in ids: _o = CreateObj() _objs.append(_o) print "-----------------------------------------------------------------" # loop through each object, and add some children for x in _objs: # create a random sequence of children (between 1 and 5) _add_count = random.randint(1,5) print "before loop: adding %s children to %s" % ( _add_count, x ) for i in xrange(0, _add_count): _child = Obj() x.add_child(_child) print "after loop: detected %s children on %s" % ( len(x.children), x ) print "---" print "-----------------------------------------------------------------" # now print the total number of children in each instance for x in _objs: print "found %s children on %s" % ( len(x.children), x )