Domanda

I have this code:

import urllib.request
import json

import pickle

import time

class Weather:

    current_temp = 0

    def __init__(self):
        json_info = get_info()
        Weather.current_temp = k_to_f(((json_info['list'][0]['main']['temp'])))
        current_city = (json_info['list'][0]['name'])
        print ('Current temperature {0} degrees F in {1} '.format(Weather.current_temp, current_city))
        map = manage_file(current_city)

    def manage_file(self, current_city):
        read_f = open('temp.txt', 'rb')
        dict = pickle.load(read_f)
        read_f.close()
        dict[time.strftime('%Y/%m/%d %H:%M:%S ') + current_city] = Weather.current_temp
        write_f = open('temp.txt', 'wb')
        return dict

    def get_info(self):
        city = input("What city would you like the weather for? ")
        url = 'http://api.openweathermap.org/data/2.5/find?q=' + city + 'mode=json'
        data = urllib.request.urlopen(url)
        data = data.read()
        json_info = json.loads(data.decode('UTF-8'))
        return json_info

    def k_to_f(self, num):
        num = (num-273.15)*1.8
        return round(num + 32, 2)
Weather()

and I am getting a traceback error of :

Traceback (most recent call last):
  File "/home/httpnick/nicks_python/new_weather.py", line 36, in <module>
    Weather()
  File "/home/httpnick/nicks_python/new_weather.py", line 14, in __init__
    map = manage_file(current_city)
  File "/home/httpnick/nicks_python/weather.py", line 36, in manage_file
     def get_info(self):
NameError: global name 'current_temp' is not defined

Can anyone spot it? I have looked for a couple hours now...

È stato utile?

Soluzione

One thing that stood out to me... is that you're not using the instance methods in the constructor. You might try to make this explicit:

def __init__(self):
    json_info = self.get_info()
    ...
    map = self.manage_file(current_city)

(Also... I'd avoid naming a variable "map", as this is a builtin function.)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top