I created three separate python scripts in the same directory. Script one contains a class that gives me my location (in json fromat) based on my IP address and stores latitude and longitude in a list called 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
The second script also contains a class that fetches a location key from a weather website using the latitude and longitude obtained in the first script
#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
A third script to display the information obtained by the other two scripts namely location and 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"
But when I run the condition.py I get the error
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'
How do I call location from geo_location.py in get_key.py ?
When you do from geo_locate import geo_locate
, you import only the class, not the entire module namespace. The location
list will be at the module root.
You should do import geo_locate
, and later, when you call the class, do it as geo_locate.geo_locate()
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.