python - 我可以使用函数参数来创建全局变量吗?

标签 python

我正在尝试创建一个函数,该函数使用其参数之一创建具有该参数名称的全局变量。当我尝试使用该函数并输入一个参数时,它只是说“名称‘矩阵’未定义”

def Gen2D(name, length):
    name = [[0 for j in range(length)] for i in range(length)]
    return(name)

Gen2D(Matrix, 12)

我希望这会导致变量名称为“Matrix”的 12 x 12 矩阵,但出现错误:“未定义名称‘Matrix’”

最佳答案

所以我不太了解这个问题的全局部分。

你可以这样做:

def Gen2D(length):
    name = [[0 for j in range(length)] for i in range(length)]
    return name

Matrix = Gen2D(12)

如果你真的想让它成为一个全局变量,你可以像这样在函数中实例化和更新一个全局变量:

def Gen2D(length):
    global Matrix 

    # Updating the value of the global matrix variable (will be updated outside the function)
    Matrix = [[0 for j in range(length)] for i in range(length)] 

# Calling the function to update the global variable.
Gen2D(12)

关于python - 我可以使用函数参数来创建全局变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58513849/

相关文章:

python - 使用分隔符将字符串/字符数组连接成单个字符串[不使用理解、映射等]

python - "ValueError: Unknown optimizer: momentum"动量优化器的正确名称?

python - 几分钟后 numpy plot 创建图形失败 idel

python - getopt.getopt 中的 temp 保持为空

python - ListView django 中的额外 "row-level"数据

python - 使用 Python 将 Unicode 编码为 iso8859-15

python - 在 Python 中调用另一个类的方法

python - 是否有任何指南可用于从 Python 2.6 开始编写 Python 以编写将来可轻松迁移到 Python 3 的应用程序?

python - 通过 cronjob 重启系统

python - 无法使用正则表达式从字符串中找到数据,而 string.find() 工作正常