无法从python中的函数内部访问全局变量

无法从python中的函数内部访问全局变量

问题描述:

下面是我的代码

global PostgresDatabaseNameSchema
global RedShiftSchemaName

PostgresDatabaseNameSchema = None
RedShiftSchemaName = None

def check_assign_global_values():
    if not PostgresDatabaseNameSchema:
        PostgresDatabaseNameSchema = "Superman"
    if not RedShiftSchemaName:
        RedShiftSchemaName = "Ironman"

check_assign_global_values()

但是我在说一个错误

Traceback (most recent call last):
  File "example.py", line 13, in <module>
    check_assign_global_values()
  File "example.py", line 8, in check_assign_global_values
    if not PostgresDatabaseNameSchema:
UnboundLocalError: local variable 'PostgresDatabaseNameSchema' referenced before assignment

那么我们不能从函数内部访问或设置全局变量吗?

So can't we access or set the global variables from inside a function ?

global应该始终在函数内定义,其原因是因为它告诉函数您要使用全局变量而不是局部变量.您可以这样做:

global should always be defined inside a function, the reason for this is because it's telling the function that you wanted to use the global variable instead of local ones. You can do so like this:

PostgresDatabaseNameSchema = None
RedShiftSchemaName = None

def check_assign_global_values():
    global PostgresDatabaseNameSchema, RedShiftSchemaName
    if not PostgresDatabaseNameSchema:
        PostgresDatabaseNameSchema = "Superman"
    if not RedShiftSchemaName:
        RedShiftSchemaName = "Ironman"

check_assign_global_values()

您应该对如何使用global有一些基本的了解.您可以搜索其他许多SO问题.例如此问题使用全局函数中的变量,而不是创建它们的函数中的变量..

You should have some basic understanding of how to use global. There is many other SO questions out there you can search. Such as this question Using global variables in a function other than the one that created them.