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

时间:2017-03-04 07:50:06

标签: python function global-variables

以下是我的代码

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

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

1 个答案:

答案 0 :(得分:2)

global应始终在函数内定义,原因是它告诉函数您想要使用全局变量而不是本地变量。你可以这样做:

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问题可以搜索。比如这个问题Using global variables in a function other than the one that created them