【问题标题】:Python: Passing variables between functionsPython:在函数之间传递变量
【发布时间】:2013-04-09 06:09:33
【问题描述】:

在过去的几个小时里,我在这里和其他地方阅读并进行了实验,但我并没有真正理解我确信是一个非常基本的概念:在不同函数之间传递值(作为变量)。

例如,我将一大堆值分配给一个函数中的列表,然后想稍后在另一个函数中使用该列表:

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. 将“列表”初始化为空列表;调用 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() 中使用它?当我看到事情发生时,我倾向于更好地理解它们,但是我看到的很多正确参数传递的例子也使用了我还不熟悉的代码,在弄清楚发生了什么的过程中,我我并没有真正掌握这个概念。我正在使用 2.7。

ETA- 过去,问过类似的问题,有人建议我使用全局变量而不是局部变量。如果它在这里也是相关的——为了我正在上课的目的,我们不允许使用全局变量。

谢谢!

【问题讨论】:

    标签: python function arguments


    【解决方案1】:

    尝试执行以下操作:

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

    您必须通过funa() 而不是age 调用它。

    【讨论】:

      【解决方案2】:

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

      定义这样的函数

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

      像这样调用函数

      function1()
      function2(a)
      

      【讨论】:

      • 缩进很差,应该先修复。其次,由于您指定了global a,因此function1() 中不需要return 语句。通常使用global 变量显然是不好的品味,但在这样一个简单的应用程序中完全没有根据。参照。 this.
      • @N.Wouda 如何在不使用全局的情况下执行此类操作?
      • def function1(): return input("Enter any number\t")。然后,a = function1()function2(a)。当然,您应该应用此代码的正确格式,但我无法在评论中实现。
      • 我必须说这只是从我正在开发的应用程序中拯救了我。一旦用户登录,该应用程序需要自动创建会话文件,并且在用户注销后也会删除该文件。我一直在寻找注销问题的解决方案,直到我偶然发现这使得局部变量成为全局变量,它今天实际上帮助并拯救了我。谢谢。
      • @OlowuAbayomi 很高兴它有帮助!
      【解决方案3】:

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

      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)
      

      【讨论】:

        【解决方案4】:

        这就是实际发生的事情:

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

        【讨论】:

          【解决方案5】:

          return 返回一个值。你给那个值取什么名字并不重要。归还它只是“传递出去”,以便其他东西可以使用它。想用就得从外面抢:

          lst = defineAList()
          useTheList(lst)
          

          defineAList 内部返回list 并不意味着“让它让程序的其余部分都可以使用该变量”。这意味着“将这个变量传递出去,让程序的其余部分有机会抓住它并使用它”。您需要将该值分配给函数之外的东西才能使用它。此外,因此,无需使用list = [] 提前定义您的列表。在defineAList 中,您创建一个新列表并将其返回;此列表与您在开头使用list = [] 定义的列表无关。

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

          【讨论】:

            【解决方案6】:

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

            list=defineAList()
            

            【讨论】:

              【解决方案7】:

              您只是错过了一个关键步骤。您必须将返回值显式传递给第二个函数。

              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)
              

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

              【讨论】:

              • 谢谢您-我很感激您不仅提供了一个示例,而且解释了它为什么会这样工作。
              猜你喜欢
              • 2013-03-07
              • 1970-01-01
              • 2019-06-28
              • 2019-06-04
              • 1970-01-01
              • 1970-01-01
              • 2020-07-02
              相关资源
              最近更新 更多