在python中访问全局变量值

2024-10-01 04:46:53 发布

您现在位置:Python中文网/ 问答频道 /正文

def definition():
    global storage_account_connection_string
    storage_account_connection_string="test"

def load_config():
    config = ConfigParser.ConfigParser()
    config.readfp(open(r'config.txt'))
    temp = config.get('API_Metrics','SCC')
    temp1 = temp.split("#")
    for conf in temp1:
        confTemp=conf.split(":")
        print "#########################################"
        print confTemp[0]
        print confTemp[1]
        print confTemp[2]
        storage_account_connection_string=confTemp[2]
        print storage_account_connection_string
        get_details()
def get_details():
    print storage_account_connection_string
    print "Blob",blob_name_filter
if __name__ == '__main_`enter code here`_':
    definition()
    load_config()`enter code here`

我的问题是,为什么连接字符串总是在get\u details()中打印“test”,尽管它在load\u config()中被分配了一些值,但我遗漏了什么吗


Tags: testconfiggetstringdefloadstorageaccount
2条回答

检查此示例:

def a():
    global g
    g = 2 # -> this is global variable


def b():
    g = 3 # -> this is function variable
    print(g)


def c():
    print(g) # -> it will use global variable

a()
b() # 3
c() # 2

在您的例子中,您需要将global添加到此函数中

....
def load_config():
    global storage_account_connection_string
    ....

我无法运行您的代码,但如果我明白了这一点,这将有助于调试:

def definition():
    global storage_account_connection_string
    storage_account_connection_string="test"

def load_config():
    global storage_account_connection_string
    storage_account_connection_string = "Whathever"

def get_details():
    print storage_account_connection_string


definition()
get_details()
load_config()
get_details()

或者这个:

storage_account_connection_string="test" # <  outside in "global scope"

def load_config():
    global storage_account_connection_string
    storage_account_connection_string = "Whathever"

def get_details():
    print storage_account_connection_string


get_details()
load_config()
get_details()

相关问题 更多 >