TypeError:password()只取1个参数(给定0)

时间:2013-06-17 09:21:55

标签: python

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

实施例

def function():
    password = blahblah

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

我对python相对比较新,并尝试了几件事,但没有一件事有效

4 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

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

def function2(): 
  print password

更好的方法是:

def function():
  return blahblah

def function2(): 
  print function()

答案 2 :(得分:0)

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

>>> def function():
        password = blahblah
        function2(password)
>>> def function2(passWord):
        print passWord
>>> function()
blahblah

答案 3 :(得分: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