繁体   English   中英

如何在另一个 function 中使用前一个 function 返回的变量? (Python)

[英]How to use a returned variable from a previous function in another function? (python)

我想在我的另一个 function 中使用从之前的 function 创建的列表。经过一些研究,似乎使用return是这样做的方式。 但是我无法让它工作。 这是我的代码:

def FunctionA():
  all_comments1 = [1,2,3,4]
  return all_comments1

def FunctionB():
  FunctionA()
  all_comment_string1 = ''.join(all_comments1)
  newlistings1 = all_comment_string1.split('\n')
  print(newlistings1)

def DoSomething():
  FunctionB()

  DoSomething()

它给了我一个错误:

NameError:未定义名称“all_comments1”

我想知道如何成功定义变量。

您必须定义一个新变量。 现在您调用 FunctionA() 但不保存其返回值。 为此,只需像这样创建一个新变量:

def FunctionA():
    all_comments1 = [1,2,3,4]
    return all_comments1

def FunctionB():
    all_comments = FunctionA()
    print(all_comments)

FunctionB()

>> [1,2,3,4]

我相信您希望在函数之间使用全局变量 将您的代码修改为以下内容:

def FunctionA():
    # Declare all_comments1 as a global variable
    global all_comments1
    all_comments1 = [1, 2, 3, 4]
    return all_comments1


def FunctionB():
    # Access global variable
    global all_comments1
    # Run functionA otherwise global variable will not be defined
    FunctionA()

    # Map objects from `all_comments1` to str, since they are int
    all_comment_string1 = ''.join(map(str, all_comments1))
    newlistings1 = all_comment_string1.split('\n')
    print(newlistings1)

def DoSomething():
    FunctionB()

DoSomething()

>> ['1234']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM