【问题标题】:Assigning a variable to a function return?将变量分配给函数返回?
【发布时间】:2020-04-08 11:18:41
【问题描述】:

我遇到了以下函数:

def load_words():
    """
    Returns a list of valid words. Words are strings of lowercase letters.

    Depending on the size of the word list, this function may
    take a while to finish.
    """
    print("Loading word list from file...")
    # inFile: file
    inFile = open(WORDLIST_FILENAME, 'r')
    # line: string
    line = inFile.readline() # reads one entire line from a file (as a string)
    # wordlist: list of strings
    wordlist = line.split()
    print("  ", len(wordlist), "words loaded.")
    return wordlist 

wordlist = load_words()

我不明白函数 load_words() 对变量 wordlist 的赋值?当变量被赋值时,函数被执行。

wordlist 是函数 load_words() 吗?还是函数load_words()的返回?

【问题讨论】:

  • wordlist = load_words() 在概念上与inFile = open(WORDLIST_FILENAME, 'r') 没有什么不同——调用一个函数,并将函数返回的任何内容分配给变量。

标签: python-3.x function variables


【解决方案1】:

当你给予时:

wordlist = load_words()

您正在运行函数load_words() 并将返回值wordlist 分配给函数外部的变量wordlist


  • 您也可以在不将其分配给变量的情况下运行函数,例如:

    load_words() 但是这里您返回的wordlist 变量不会存储在python(我的意思是当前的shell)中以供进一步使用。函数内部的wordlist是一个局部变量,只在函数内部有效。

  • 所以当你给wordlist = load_words()时,wordlist现在变成了一个全局变量,这样你就可以在需要的时候调用它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-23
    • 2017-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多