简体   繁体   English

如何跨函数传递变量?

[英]How do I pass variables across functions?

I want to pass values (as variables) between different functions.我想在不同的函数之间传递值(作为变量)。

For example, I assign values to a list in one function, then I want to use that list in another function:例如,我将值分配给一个 function 中的列表,然后我想在另一个 function 中使用该列表:

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()

I would expect this to do as follows:我希望这样做如下:

  1. Initialize 'list' as an empty list;将'list'初始化为空列表; call main (this, at least, I know I've got right...)打电话给 main (这,至少,我知道我做对了......)
  2. Within defineAList(), assign certain values into the list;在 defineAList() 中,将某些值分配到列表中; then pass the new list back into main()然后将新列表传递回 main()
  3. Within main(), call useTheList(list)在 main() 中,调用 useTheList(list)
  4. 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'包含在useTheList function的参数中,我希望useTheList现在将使用defineAList()定义的列表,而不是调用main之前定义的空列表。

However, my output is:但是,我的 output 是:

For checking purposes: in defineAList, list is ['1', '2', '3']
For checking purposes: in useTheList, list is []

"return" does not do what I expected. “返回”没有达到我的预期。 What does it actually do?它实际上是做什么的? How do I take the list from defineAList() and use it within useTheList()?如何从 defineAList() 中获取列表并在 useTheList() 中使用它?

I don't want to use global variables.我不想使用全局变量。

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_list and 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()) 

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.您必须实际捕获调用范围内的返回值,然后将其用于后续操作。

return returns a value. return返回一个值。 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:如果你想使用它,你必须从外面抓住它:

lst = defineAList()
useTheList(lst)

Returning list from inside defineAList doesn't mean "make it so the whole rest of the program can use that variable".defineAList内部返回list并不意味着“让它让程序的整个其余部分都可以使用该变量”。 It means "pass the value of 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 = [] .此外,因此,无需使用list = []提前定义您的列表。 Inside defineAList , you create a new list and return it;defineAList中,您创建一个新列表并将其返回; this list has no relationship to the one you defined with list = [] at the beginning.此列表与您在开头使用list = []定义的列表没有关系。

Incidentally, I changed your variable name from list to lst .顺便说一句,我将您的变量名从list更改为lst It's not a good idea to use list as a variable name because that is already the name of a built-in Python type.使用list作为变量名并不是一个好主意,因为这已经是 Python 内置类型的名称。 If you make your own variable called list , you won't be able to access the builtin one anymore.如果您创建自己的变量list ,您将无法再访问内置变量。

你的回报是没有用的,如果你不分配它

list=defineAList()

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)

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)

call the functions like this像这样调用函数

function1()
function2(a)

Try do the following:尝试执行以下操作:

def funa():
    name=("Bob")
    age=("42")
    return name, age

def funb():
    name, age=funa()
    print(name)
    print(age)

funb()

Happens that you gotta call it via funa() instead of age .碰巧你必须通过funa()而不是age来调用它。

Just return it.就退货吧。

Example:例子:

def initiate_excel_corvert():
 
    df = pd.ExcelFile('empty_book.xlsx').parse('Sheet')
    x=[]
    x.append(df['Numbers'])
    x.clear()
    x.extend(df['Numbers'])
    print(len(x))
    print('\n')
    len_of_column_0 =+1 + len(x)
    print("+ add-on ::")
    print(len_of_column_0)
    print('\n')
    
    return render_template('index.html'), insert_into_excel(len_of_column_0)
    
def insert_into_excel(len_of_column_0):
    print ("len_of_column_0 = ", len_of_column_0)
    print('\n')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM