2017-06-23 38 views
0

我想弄清楚如何通过引用传递这些值。Python。我的传递变量怎么没有被更新?他们是不是通过引用传递?

我想打印“aNumber”变量值为100,但没有更新。

我想将“someList”列表打印为具有值(100,100)的列表,但它未被更新。

任何想法为什么?

非常感谢。

这是程序:

################################# 

def makeIt100(aVariable): 
    aVariable = 100 

aNumber = 7 
print(aNumber) 

makeIt100(aNumber) 

print(aNumber) 

################################## 

def changeTheList(aList): 
    aList = (100, 100) 

someList = (7, 7) 
print(someList) 

changeTheList(someList) 

print(someList) 

################################## 

这是结果我得到:

7 
7 
(7, 7) 
(7, 7) 
+0

这将清除您的误解:https://nedbatchelder.com/text/names1.html – chepner

+1

可能的重复[如何通过引用传递变量?](https://stackoverflow.com/questions/986006/how-do-i-pass-a-by-reference) – daemon24

+0

重复的https://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference –

回答

2

尝试是这样的,用一个return语句在你的函数:

def makeit100(): 
    return 100 


aVariable = 7 
print aVariable #(should print 7) 
aVariable = makeit100() 
print aVariable #(should print 100) 

从本质上讲,在你定义的函数中使用的变量与外部变量并不相同,即使如此它有相同的名字;它是在函数被调用时创建的,然后被处理掉。

+0

好的,所以没有办法做我想做的事情?就像你在C++中做的那样?所以我被迫返回? –

+0

我不相信你可以这样做;退货声明可能是您唯一的选择。这里有一个类似的问题:https://stackoverflow.com/questions/575196/in-python-why-can-a-function-modify-some-arguments-as-perceived-by-the-caller – iammax

相关问题