-4

我正在尝试在一个函数中打印一个变量,而该变量在另一个函数中。

例子

def function():
    password = blahblah

def function2():
    .....
    print password

我对 python 比较陌生,已经尝试了几件事,但都没有奏效

4

4 回答 4

0

password从中返回function,并在其中使用返回值function2

您不能从函数外部访问函数内部的变量,因为它们是该函数的本地变量。

def function(): 
    password = blahblah    # This variable is local to function
                           # and can't be accessed outside of the function

    return password        # But you can return the value of password using 
                           # the `return` statement.

def function2(): 
    print function()      #use the retured value from function
于 2013-06-17T09:23:38.063 回答
0

您在 的范围内创建并访问了变量function,一旦function()完成执行,它就会被销毁。

password=None
def function():
  global password 
  password = blahblah

def function2(): 
  print password

更好的方法是:

def function():
  return blahblah

def function2(): 
  print function()
于 2013-06-17T09:24:16.627 回答
0

尝试将变量作为参数传递给第二个函数,如下所示

>>> def function():
        password = blahblah
        function2(password)
>>> def function2(passWord):
        print passWord
>>> function()
blahblah
于 2013-06-17T09:25:10.833 回答
0
def function1():
    return 'blahblah'  #return value from given function



def function2(param):  # accept a parameter
    if callable(param):  # if is callable (ie. function)... 
         print param()   # ...print value by calling it
    else:
         print param     # otherwise print just the value

>>> function2(function1)
blahblah
于 2013-06-17T09:25:29.040 回答