我在同一目录中创建了三个单独的python脚本。脚本一包含一个类,根据我的IP地址给出我的位置(在json fromat中),并将纬度和经度存储在名为 location
的列表中#geo_location.py
import json
import urllib2
class geo_locate:
def __init__(self,location_url):
self.location_url=location_url
global location
location=[]
def locate(self):
req=urllib2.Request(self.location_url)
res=urllib2.urlopen(req)
j=json.loads(res.read())
location.append(j['latitude'])
location.append(j['longitude'])
return location
第二个脚本还包含一个类,该类使用在第一个脚本中获得的纬度和经度从天气网站获取位置键
#get_key.py
import json
import requests
from geo_locate import geo_locate
class get_key():
def __init__(self,location_key_url,key):
self.location_key_url=location_key_url
self.key=key
def locate_key(self):
api=[]
link=self.location_key_url + "=" + str(geo_locate.location[0]) + "," + str(geo_locate.location[1]) + "&apikey=" + self.key
res=requests.get(link)
j=json.loads(res.text)
api.append(j['Key'])
return api
显示其他两个脚本获取的信息的第三个脚本,即 location和api
#condition.py
from urllib2 import URLError
from geo_locate import geo_locate
from get_key import get_key
url='http://dataservice.accuweather.com/locations/v1/cities/'
api='<api key here>'
send_url='http://freegeoip.net/json'
class main:
def __init__(self):
geo_locate(send_url).locate()
get_key(url,api).locate_key()
if __name__=='__main__':
try:
main()
except URLError,e:
print e.reason,"\nPlease check connection"
但是当我运行 condition.py 时,我收到错误
Traceback (most recent call last):
File "/home/c0d3d/Documents/accupy/accupy/condition.py", line 18, in <module>
main()
File "/home/c0d3d/Documents/accupy/accupy/condition.py", line 12, in __init__
get_key(url,api).locate_key()
File "/home/c0d3d/Documents/accupy/accupy/get_key.py", line 15, in
locate_key
link=self.location_key_url + "=" + str(geo_locate.location[0]) + "," +
str(geo_locate.location[1]) + "&apikey=" + self.key
AttributeError: class geo_locate has no attribute 'location'
如何从 get_key.py 中的 geo_location.py 调用位置?
答案 0 :(得分:0)
执行from geo_locate import geo_locate
时,只导入类,而不导入整个模块名称空间。 location
列表将位于模块根目录。
您应该import geo_locate
,之后,当您致电课程时,请执行geo_locate.geo_locate()
。