Python看不到全局变量b

2024-09-28 23:25:42 发布

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

尽管我将变量指定为函数中的global,如下所示:

def SECdownload(year, month):
    import os
    from urllib.request import urlopen
    root = None
    feedFile = None
    feedData = None
    good_read = False
    itemIndex = 0
    edgarFilingsFeed = 'http://www.sec.gov/Archives/edgar/monthly/xbrlrss-' + str(year) + '-' + str(month).zfill(2) + '.xml'
    return edgarFilingsFeed
    #print( edgarFilingsFeed ) #from the slides
    if not os.path.exists( "sec/" + str(year) ):
        os.makedirs( "sec/" + str(year) )
    if not os.path.exists( "sec/" + str(year) + '/' + str(month).zfill(2) ):
        os.makedirs( "sec/" + str(year) + '/' + str(month).zfill(2) )
    global target_dir
    target_dir = "sec/" + str(year) + '/' + str(month).zfill(2) + '/'

然后我导入函数,然后在Python UI(Windows)中运行它,如下所示:

>>> from df import SECdownload
>>> SECdownload(2012,4)

为什么在Shell中键入变量target_dir时会得到:

>>> target_dir
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
    target_dir

NameError: name 'target_dir' is not defined

当我在函数中清楚地声明variableglobal时,这怎么可能呢?你知道吗


Tags: 函数fromimportnonetargetosdirsec
2条回答

处理全局变量的代码无法访问,因为这行:

return edgarFilingsFeed

函数在创建它们的上下文中工作。也就是说,它们使用的任何全局变量都是创建函数的模块的本地变量。你知道吗

例如:

男/女:

def a(val):
    global x
    x = val

你知道吗主.py你知道吗

from m import a
a(10)
import m
print(m.x)

产生10

相关问题 更多 >