如何跨函数传递变量?[重复]

2025-02-20 09:24:00
admin
原创
66
摘要:问题描述:我想在不同的函数之间传递值(作为变量)。例如,我在一个函数中为列表分配值,然后我想在另一个函数中使用该列表:list = [] def defineAList(): list = ['1','2','3'] print "For checking purposes: in...

问题描述:

我想在不同的函数之间传递值(作为变量)。

例如,我在一个函数中为列表分配值,然后我想在另一个函数中使用该列表:

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

我希望这样做:

  1. 将“list”初始化为空列表;调用main(至少我知道我是对的......)

  2. 在 defineAList() 中,将某些值分配到列表中;然后将新列表传回 main()

  3. 在 main() 中,调用 useTheList(list)

  4. 由于“list”包含在 useTheList 函数的参数中,我希望 useTheList 现在将使用 defineAList() 定义的列表,而不是调用 main 之前定义的空列表。

但是,我的输出是:

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

“return” 并没有达到我的预期。它实际上做了什么?如何从 defineAList() 中获取列表并在 useTheList() 中使用它?

我不想使用全局变量。


解决方案 1:

以下是实际发生的情况:

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

这就是你想要的:

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

您甚至可以跳过临时值returned_list并将返回值直接传递给useTheList

def main():
    # passed_list inside useTheList is set to what is returned from defineAList
    useTheList(defineAList()) 

解决方案 2:

您只是缺少一个关键步骤。您必须明确地将返回值传递给第二个函数。

def main():
    l = defineAList()
    useTheList(l)

或者:

def main():
    useTheList(defineAList())

或者(虽然你不应该这样做!乍一看可能不错,但从长远来看全局变量只会让你痛苦不堪):

l = []

def defineAList():
    global l
    l.extend(['1','2','3'])

def main():
    global l
    defineAList()
    useTheList(l)

函数返回一个值,但它不会像代码所假设的那样在任何类型的全局命名空间中创建符号。您必须实际捕获调用范围内的返回值,然后将其用于后续操作。

解决方案 3:

return返回一个值。你给这个值起什么名字并不重要。返回它只是“传递出去”,以便其他东西可以使用它。如果你想使用它,你必须从外部获取它:

lst = defineAList()
useTheList(lst)

list从内部返回defineAList并不意味着“让程序的其余部分都可以使用该变量”。它意味着“将该变量的值传递出去,让程序的其余部分有机会获取并使用它”。您需要将该值分配给函数外部的某个对象才能使用它。此外,正因为如此,无需提前使用 定义列表list = []。在 内部defineAList,您创建一个新列表并返回它;此列表与您在开始时定义的列表没有任何关系list = []

顺便说一句,我将您的变量名称从 改为listlst将其用作变量名称不是一个好主意,list因为这已经是内置 Python 类型的名称。如果您创建自己的变量名为list,您将无法再访问内置变量。

解决方案 4:

如果你不分配,你的回报就毫无用处

list=defineAList()

解决方案 5:

阅读命名空间的概念。在函数中分配变量时,您只能在该函数的命名空间中分配它。但显然您想在所有函数之间使用它。

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

或者,你可以将其传递出去:

def main():
    new_list = defineAList()
    useTheList(new_list)

解决方案 6:

将变量从一个函数作为参数传递给其他函数可以像这样完成

定义这样的函数

def function1():
    global a
    a=input("Enter any number    ")
 
def function2(argument):
    print ("this is the entered number - ",argument)

像这样调用函数

function1()
function2(a)

解决方案 7:

尝试做以下事情:

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

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

funb()

碰巧你必须通过funa()而不是 来调用它age

解决方案 8:

只需将其退回即可。

例子:

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('
')
    len_of_column_0 =+1 + len(x)
    print("+ add-on ::")
    print(len_of_column_0)
    print('
')
    
    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('
')
相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   3970  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   2740  
  本文介绍了以下10款项目管理软件工具:禅道项目管理软件、Freshdesk、ClickUp、nTask、Hubstaff、Plutio、Productive、Targa、Bonsai、Wrike。在当今快速变化的商业环境中,项目管理已成为企业成功的关键因素之一。然而,许多企业在项目管理过程中面临着诸多痛点,如任务分配不...
项目管理系统   79  
  本文介绍了以下10款项目管理软件工具:禅道项目管理软件、Monday、TeamGantt、Filestage、Chanty、Visor、Smartsheet、Productive、Quire、Planview。在当今快速变化的商业环境中,项目管理已成为企业成功的关键因素之一。然而,许多项目经理和团队在管理复杂项目时,常...
开源项目管理工具   87  
  本文介绍了以下10款项目管理软件工具:禅道项目管理软件、Smartsheet、GanttPRO、Backlog、Visor、ResourceGuru、Productive、Xebrio、Hive、Quire。在当今快节奏的商业环境中,项目管理已成为企业成功的关键因素之一。然而,许多企业在选择项目管理工具时常常面临困惑:...
项目管理系统   74  
热门文章
项目管理软件有哪些?
曾咪二维码

扫码咨询,免费领取项目管理大礼包!

云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用