NameError: global name 'name' is not defined (while it is defined.)

NameError: global name 'name' is not defined (while it is defined.)

我是 python 的新手,现在正在用它制作一些程序。

我有两个文件,分别是trans.pymain.py

trans.py,

from math import *
from numpy import *


def matrix_T(d): 
    global mat_A, mat_B, mat_C, mat_D   
    temp_A, temp_B, temp_C, temp_D = mat_A, mat_B, mat_C, mat_D
    mat_A = 1.0*temp_A + d*temp_C     
    mat_B = 1.0*temp_B + d*temp_D
    mat_C = 1.0*temp_C
    mat_D = 1.0*temp_D

main.py,

from trans import *

global mat_A, mat_B, mat_C, mat_D
mat_A = 1.0
mat_B = 0.0
mat_C = 0.0
mat_D = 1.0

print(mat_A, mat_B, mat_C, mat_D)

matrix_T(0.0)

print(mat_A, mat_B, mat_C, mat_D)

当我 运行 main.py 时,当然会出现此错误。

Traceback (most recent call last):
  File "main.py", line 11, in <module>
    matrix_T(0.0)
  File "trans.py", line 6, in matrix_T
    temp_A, temp_B, temp_C, temp_D = mat_A. mat_B, mat_C, mat_D
NameError: global name 'mat_A' is not defined

既然我以为我定义了全局变量mat_A到mat_D,我怎么能避免这个问题呢?

在此先感谢。

第一点:global <name>没有定义一个变量,它只是告诉运行时在这个函数中,“<name>”必须在 "global" 命名空间而不是本地命名空间中查找。

第二点:在Python中,"global"命名空间实际上是指当前模块的顶级命名空间。这是您将在 Python 中获得的最多 "global" 命名空间(希望如此)。因此,在另一个模块中使用相同名称定义变量不会使它们可用于您的函数(这是一件好事)。

最后一点:无论如何不要使用全局变量。将需要的参数传递给您的函数,并使您的函数 return 计算值。全局变量是邪恶的。