您的位置:首页 > 编程语言 > Python开发

python-关于函数间参数传递问题(注意理解,很容易混淆)

2017-04-10 11:36 681 查看
先看段代码,关于递归生成链表的问题,先自己判断会输出什么,再看结果

class Node:
def __init__(self):
self.val = None
self.next = None

def ccc(node,x,res):
if res == x:
return
node = Node()
node.val = res
res = res + 1
ccc(node.next,x,res)

x = Node()
ccc(x,6,0)
print x.val
结果输出为None,为什么呢?明明已经调用了ccc函数,也把头结点穿进去了,怎么会这样呢?原因在于首先执行了x = Node(),我们假设给x分配了001的内存地址,这个内存里面放的就是Node类的一个实例,接着我们调用了ccc函数,将x传递给了ccc函数的参量node,现在node也指向了001的内存地址,到这似乎没什么问题,但接下来node = Node()这一步就是问题关键所在,现在node不在指向001的内存地址,而是被新分配了一个内存地址002,里面也存放的是Node类的一个实例,而我们头结点所指向的内存并不被ccc函数执行,所以001内存里的数据并没有因为ccc的调用而更新。

好了既然知道了问题所在,我们修改下程序后,看下面这段代码

class Node:
def __init__(self):
self.val = None
self.next = None

def ccc(node,x,res):
if res == x:
return
if res == 0:
node.val = res
res = res + 1
ccc(node,x,res)
else:
node.next = Node()
node.next.val = res
res = res + 1
ccc(node.next,x,res)

s = Node()
ccc(s,6,0)
while s != None:
print s.val
s = s.next


结果输出为0,1,2,3,4,5.正确
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: