本文介绍了无法从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.
这篇关于无法从python中的函数内部访问全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!