is None object mutable in python? -


i have tuple this.

t = (5, (3, (20, none, none), (21, none, none)), (10, (1, none, none), none)) 

i build tree it. tree class this.

class treenode(object):     def __init__(self,x=none,l=none,r=none):         self.x = x         self.l = l  # left node         self.r = r  # right node 

i building tree recursively. check if current node none, set current node new treenode class. doesn't work expected.

def build(current_node, tupl):     if tupl:         if current_node none:             current_node  = treenode() # think removes link trees node.         current_node.x = tupl[0]         build(current_node.l, tupl[1])         build(current_node.r,tupl[2]) 

here how call build function

root = treenode() # treenode tree class build(root,t) # try print tree level level tree has root node 

but build function works fine.

def build(curr,t):     if t:         curr.x = t[0]         try:             if t[1] not none:                 curr.l = treenode()                 build(curr.l,t[1])         except exception:             pass         try:             if t[2] not none:                 curr.r = treenode()                 build(curr.r,t[2])         except exception:             pass 

i trying understand why first build function failing.

in python, can't reassign variables within function, , have values visible calling context. calling current_node = treenode(), current_node assigned new object not visible outside.

def build(current_node, tupl):     if tupl:         if current_node none:             current_node  = treenode()         current_node.x = tupl[0]          build(current_node.l, tupl[1])         build(current_node.r,tupl[2]) 

in second example, passing in treenode instance, manipulating it's attributes , not reassigning it. therefore, curr.l/curr.r in current context , curr in next call still refer same object.

def build(curr,t):     if t:         curr.x = t[0]      ....     if t[2] none:         curr.r = treenode()      ....      # reference link not broken      build(curr.r, t[2]) 

Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -