[英]Python cannot see global variable
雖然我在這樣的函數中指定一個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
當我在函數內部明確聲明 variable
是global
variable
時,這怎么可能?
由於以下這一行,您無法處理全局變量的代碼:
return edgarFilingsFeed
函數在創建它們的上下文中工作。 也就是說,他們使用的所有全局變量都在創建該函數的模塊本地。
例如:
m.py:
def a(val):
global x
x = val
main.py
from m import a
a(10)
import m
print(m.x)
產生10
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.