【问题标题】:Passing variables between functions in Python在 Python 中的函数之间传递变量
【发布时间】:2016-10-10 16:19:35
【问题描述】:

好的,所以我很难理解在函数之间传递变量:

我似乎找不到一个明确的例子。

我不想在 funb() 中运行 funa()。

def funa():
    name=input("what is your name?")
    age=input("how old are you?")
    return name, age

funa()

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

funb()

【问题讨论】:

  • Daniel 是对的,但这是您从阅读 Python 简介或变量和函数教程中学到的东西。

标签: python


【解决方案1】:

由于funa 返回 name 和 age 的值,您需要将它们分配给局部变量,然后将它们传递给 funb:

name, age = funa()
funb(name, age)

注意,函数内部和外部的名称没有联系;这也可以:

foo, bar = funa()
funb(foo, bar)

【讨论】:

  • 那么为什么这样做比不使用全局变量更好呢?
  • 一方面,因为那样您将依赖自始至终使用的相同名称。
【解决方案2】:

将其视为通过使用变量和函数参数作为对这些对象的引用来传递对象。当我更新您的示例时,我还更改了变量的名称,以便清楚地知道对象存在于不同命名空间中的不同变量中。

def funa():
    name=input("what is your name?")
    age=input("how old are you?")
    return name, age                   # return objects in name, age

my_name, my_age = funa()               # store returned name, age objects
                                       # in global variables

def funb(some_name, some_age):         # a function that takes name and 
                                       # age objects
    print(some_name)
    print(some_age)

funb(my_name, my_age)                  # use the name, age objects in the
                                       # global variables to call the function

【讨论】:

  • 谢谢,这很清楚,但我仍然不明白为什么首先使用函数而不是使用全局变量,如果 name 和 age 最终成为全局变量?
  • 这取决于您对该计划的目标是什么。随着程序的增长,除非您封装数据,否则它会变得难以管理——这意味着要避免使用全局变量。其他问题是关于您如何使用该功能。假设将来您想维护一个dict 的名称:年龄对。现在你的名字,年龄全局变量是有问题的。您将不得不更改函数以及使用数据的所有位置。
【解决方案3】:

因为它返回一个元组,你可以简单地用*解压它:

funb(*funa())

它应该看起来像这样:

def funa():
  # funa stuff
  return name, age

def funb(name, age):
  # funb stuff
  print ()

funb(*funa())

【讨论】:

    猜你喜欢
    • 2013-04-09
    • 2013-03-07
    • 1970-01-01
    • 2019-06-28
    • 2019-06-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多