Skip to main content
 首页 » 编程设计

python之如何处理模块中的全局变量

2025年05月04日18me-sa

我尝试对 OpenWeatherMap 进行非阻塞 API 调用,但我的问题是:

当我对文件进行测试并运行它时,global api 正在生效,但是当导入函数时,global 不再起作用,并且 api 没有改变:api = ""?

在声明函数之后,我输入了 global api,然后当我使用 print 'The API link is: ' + api 时,我得到了准确的 api ,但是 global dident 生效了!

这是代码:https://github.com/abdelouahabb/tornadowm/blob/master/tornadowm.py#L62

我做错了什么?

导入文件时:

from tornadowm import * 
forecast('daily', q='london', lang='fr') 
The API link is: http://api.openweathermap.org/data/2.5/forecast/daily?lang=fr&q=london 
api 
Out[5]: '' 

当执行文件而不是导入文件时:

runfile('C:/Python27/Lib/site-packages/tornadowm.py', wdir='C:/Python27/Lib/site-packages') 
 
forecast('daily', q='london', lang='fr') 
The API link is: http://api.openweathermap.org/data/2.5/forecast/daily?lang=fr&q=london 
 
api 
Out[8]: 'http://api.openweathermap.org/data/2.5/forecast/daily?lang=fr&q=london' 

编辑:如果 Git 更新了,这里是代码:

from tornado.httpclient import AsyncHTTPClient 
import json 
import xml.etree.ElementTree as ET 
 
http_client = AsyncHTTPClient() 
url = '' 
response = '' 
args = [] 
link = 'http://api.openweathermap.org/data/2.5/' 
api = '' 
result = {} 
way = '' 
 
 
def forecast(way, **kwargs): 
    global api 
    if way in ('weather', 'forecast', 'daily', 'find'): 
        if way == 'daily': 
            way = 'forecast/daily?' 
        else: 
            way += '?' 
        for i, j in kwargs.iteritems(): 
            args.append('&{0}={1}'.format(i, j)) 
        a = ''.join(set(args)) 
        api = (link + way + a.replace(' ', '+')).replace('?&', '?') 
        print 'The API link is: ' + api 
 
        def handle_request(resp): 
            global response 
            if resp.error: 
                print "Error:", resp.error 
            else: 
                response = resp.body 
 
        http_client.fetch(api, handle_request) 
    else: 
        print "please put a way: 'weather', 'forecast', 'daily', 'find' " 
 
 
def get_result(): 
    global result 
    if response.startswith('{'): 
        print 'the result is JSON, stored in the variable result' 
        result = json.loads(response) 
 
    elif response.startswith('<'): 
        print 'the result is XML, parse the result variable to work on the nodes,' 
        print 'or, use response to see the raw result' 
        result = ET.fromstring(response) 
 
    else: 
        print '''Sorry, no valid response, or you used a parameter that is not compatible with the way!\n please check http://www.openweathermap.com/api for more informations'' 

请您参考如下方法:

这是使用 global 的副作用。

当你执行 from tornadowm import * 时,你的 forecast() 函数,我们可以比喻地说,是“独立”的,而不是“硬链接(hard link)”到你的全局空间了。

为什么?因为您对全局 api 所做的任何影响都将随着您的函数“结束”,并且全局空间中 api = "" 的定义将优先。

此外,作为旁注,使用 from something import * 并不是一个好的做法。您应该执行 from tornadowm import forecast 或者更好,import tornadown 然后使用 tornadowm.forecast()。

  • 或

更好的是,我刚刚注意到您的 forecast() 函数没有返回任何内容。从技术上讲,它不再是一个函数,而是一个过程(过程就像一个函数,但它什么都不返回,它只是“做”一些事情)。

不使用global,您应该在此函数中定义api,然后从中返回api。像这样:

def forecast(blablabla): 
    api = "something" 
    blablabla 
    return api 

然后

import tornadowm 
api = tornadown.forecast(something) 

大功告成。