Python 1中的回溯错误

时间:2014-04-24 22:00:39

标签: python traceback

我有这段代码:

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()

我收到的追溯错误是:

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

有人能发现吗?我现在看了几个小时......

1 个答案:

答案 0 :(得分:0)

有一件事让我感到高兴......是你在构造函数中没有使用实例方法。您可以尝试明确说明:

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

(另外......我避免命名变量&#34; map&#34;,因为这是一个内置函数。)