Python,传递给另一个函数的多个变量的简单示例

Vik*_*tor -1 python variables function

我知道之前已经解释过这个问题了,但是我仍然无法弄清楚我的场景,我解释的很简单:

def func1 ():
  a = 1
  b = 2
  print a + b

def func2 ():
  c = 3
  d = 4
  e = a * c
  f = b + d

func1()
func2()
Run Code Online (Sandbox Code Playgroud)

当像这样运行时:

$ ./test1.py 
3
Traceback (most recent call last):
  File "./test1.py", line 18, in <module>
    func2()
  File "./test1.py", line 14, in func2
    e = a * c
NameError: global name 'a' is not defined
Run Code Online (Sandbox Code Playgroud)

简单的问题是,如何更改上面的代码,以便func2存储来自func1的变量?

Ewa*_*wan 5

不是像其他答案中提到的那样使变量成为全局变量,而是将它们返回func1并使用它们func2.

def func1():
    a = 1
    b = 2
    print a + b
    return a, b

def func2(a, b):
    c = 3
    d = 4
    e = a * c
    f = b + d

func2(*func1())
Run Code Online (Sandbox Code Playgroud)

因为我们在func1()这些中返回多个变量来作为元组(a, b).

而不是将其作为单个变量传递给func2我们必须将它们解压缩为2个变量.

这是一个很好的问题和答案的主题*args **kwargs.