Python:在函数之间传递变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16043797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: Passing variables between functions
提问by user2113818
I've spent the past few hours reading around in here and elsewhere, as well as experimenting, but I'm not really understanding what I am sure is a very basic concept: passing values (as variables) between different functions.
在过去的几个小时里,我在这里和其他地方阅读并进行了实验,但我并没有真正理解我确定的一个非常基本的概念:在不同函数之间传递值(作为变量)。
For example, I assign a whole bunch of values to a list in one function, then want to use that list in another function later:
例如,我将一大堆值分配给一个函数中的列表,然后想稍后在另一个函数中使用该列表:
list = []
def defineAList():
list = ['1','2','3']
print "For checking purposes: in defineAList, list is",list
return list
def useTheList(list):
print "For checking purposes: in useTheList, list is",list
def main():
defineAList()
useTheList(list)
main()
Based on my understanding of what function arguments do, I would expect this to do as follows:
根据我对函数参数的作用的理解,我希望这样做如下:
- Initialize 'list' as an empty list; call main (this, at least, I know I've got right...)
- Within defineAList(), assign certain values into the list; then pass the new list back into main()
- Within main(), call useTheList(list)
- Since 'list' is included in the parameters of the useTheList function, I would expect that useTheList would now use the list as defined by defineAList(), NOT the empty list defined before calling main.
- 将 'list' 初始化为空列表;调用 main (至少,我知道我是对的......)
- 在defineAList() 中,将某些值分配到列表中;然后将新列表传回 main()
- 在 main() 中,调用 useTheList(list)
- 由于“list”包含在 useTheList 函数的参数中,我希望 useTheList 现在将使用由 defineAList() 定义的列表,而不是在调用 main 之前定义的空列表。
However, this is obviously a faulty understanding. My output is:
然而,这显然是一种错误的理解。我的输出是:
For checking purposes: in defineAList, list is ['1', '2', '3']
For checking purposes: in useTheList, list is []
So, since "return" obviously does not do what I think it does, or at least it does not do it the way I think it should... what does it actually do? Could you please show me, using this example, what I would have to do to take the list from defineAList() and use it within useTheList()? I tend to understand things better when I see them happening, but a lot of the examples of proper argument-passing I've seen also use code I'm not familiar with yet, and in the process of figuring out what's going on, I'm not really getting a handle on this concept. I'm using 2.7.
所以,由于“返回”显然没有按照我的想法去做,或者至少它没有按照我认为的方式去做……它实际上做了什么?你能否用这个例子告诉我,我需要做什么才能从defineAList()中获取列表并在useTheList()中使用它?当我看到事情发生时,我倾向于更好地理解它们,但是我见过的许多正确传递参数的示例也使用了我还不熟悉的代码,并且在弄清楚发生了什么的过程中,我我并没有真正掌握这个概念。我正在使用 2.7。
ETA- in the past, asking a similar question, it was suggested that I use a global variable instead of just locals. If it will be relevant here also- for the purposes of the class I'm taking, we're not permitted to use globals.
ETA- 过去,问一个类似的问题,有人建议我使用全局变量而不仅仅是本地变量。如果它也与此处相关 - 就我正在上课的目的而言,我们不允许使用全局变量。
Thank you!
谢谢!
采纳答案by Pavel Anossov
This is what is actually happening:
这是实际发生的事情:
global_list = []
def defineAList():
local_list = ['1','2','3']
print "For checking purposes: in defineAList, list is", local_list
return local_list
def useTheList(passed_list):
print "For checking purposes: in useTheList, list is", passed_list
def main():
# returned list is ignored
returned_list = defineAList()
# passed_list inside useTheList is set to global_list
useTheList(global_list)
main()
This is what you want:
这就是你想要的:
def defineAList():
local_list = ['1','2','3']
print "For checking purposes: in defineAList, list is", local_list
return local_list
def useTheList(passed_list):
print "For checking purposes: in useTheList, list is", passed_list
def main():
# returned list is ignored
returned_list = defineAList()
# passed_list inside useTheList is set to what is returned from defineAList
useTheList(returned_list)
main()
You can even skip the temporary returned_listand pass the returned value directly to useTheList:
您甚至可以跳过临时returned_list并将返回值直接传递给useTheList:
def main():
# passed_list inside useTheList is set to what is returned from defineAList
useTheList(defineAList())
回答by Silas Ray
You're just missing one critical step. You have to explicitly pass the return value in to the second function.
你只是错过了一个关键步骤。您必须显式地将返回值传递给第二个函数。
def main():
l = defineAList()
useTheList(l)
Alternatively:
或者:
def main():
useTheList(defineAList())
Or (though you shouldn't do this! It might seem nice at first, but globals just cause you grief in the long run.):
或者(虽然你不应该这样做!起初看起来不错,但从长远来看,全局变量只会让你感到悲伤。):
l = []
def defineAList():
global l
l.extend(['1','2','3'])
def main():
global l
defineAList()
useTheList(l)
The function returns a value, but it doesn't create the symbol in any sort of global namespace as your code assumes. You have to actually capture the return value in the calling scope and then use it for subsequent operations.
该函数返回一个值,但它不会像您的代码假定的那样在任何类型的全局命名空间中创建符号。您必须在调用范围内实际捕获返回值,然后将其用于后续操作。
回答by bobrobbob
Your return is useless if you don't assign it
如果您不分配它,您的回报将毫无用处
list=defineAList()
回答by BrenBarn
returnreturns a value. It doesn't matter what name you gave to that value. Returning it just "passes it out" so that something else can use it. If you want to use it, you have to grab it from outside:
return返回一个值。你给那个值取什么名字并不重要。返回它只是“传递出去”,以便其他人可以使用它。如果你想使用它,你必须从外面抓住它:
lst = defineAList()
useTheList(lst)
Returning listfrom inside defineAListdoesn't mean "make it so the whole rest of the program can use that variable". It means "pass this variable out and give the rest of the program one chance to grab it and use it". You need to assign that value to something outside the function in order to make use of it. Also, because of this, there is no need to define your list ahead of time with list = []. Inside defineAList, you create a new list and return it; this list has no relationship to the one you defined with list = []at the beginning.
list从内部返回defineAList并不意味着“让它让整个程序的其余部分都可以使用该变量”。它的意思是“传递这个变量,让程序的其余部分有机会抓住它并使用它”。您需要将该值分配给函数之外的某些内容才能使用它。此外,因此,无需提前使用list = []. 在里面defineAList,你创建一个新列表并返回它;此列表与您list = []在开始时定义的列表无关。
Incidentally, I changed your variable name from listto lst. It's not a good idea to use listas a variable name because that is already the name of a built-in Python type. If you make your own variable called list, you won't be able to access the builtin one anymore.
顺便说一句,我将您的变量名称从 更改list为lst. list用作变量名不是一个好主意,因为这已经是内置 Python 类型的名称。如果您将自己的变量称为list,您将无法再访问内置变量。
回答by Benjamin
Read up the concept of a name space. When you assign a variable in a function, you only assign it in the namespace of this function. But clearly you want to use it between all functions.
阅读名称空间的概念。当你在函数中分配一个变量时,你只能在这个函数的命名空间中分配它。但显然你想在所有功能之间使用它。
def defineAList():
#list = ['1','2','3'] this creates a new list, named list in the current namespace.
#same name, different list!
list.extend['1', '2', '3', '4'] #this uses a method of the existing list, which is in an outer namespace
print "For checking purposes: in defineAList, list is",list
return list
Alternatively, you can pass it around:
或者,您可以传递它:
def main():
new_list = defineAList()
useTheList(new_list)
回答by Pb Studies
passing variable from one function as argument to other functions can be done like this
可以像这样将变量从一个函数作为参数传递给其他函数
define functions like this
像这样定义函数
def function1(): global a a=input("Enter any number\t") def function2(argument): print ("this is the entered number - ",argument)
def function1(): global a a=input("Enter any number\t") def function2(argument): print ("this is the entered number - ",argument)
call the functions like this
像这样调用函数
function1()
function2(a)

