在python中创建用于获取天气数据的类时出现Getting Attribute错误



当我直接执行这个方法时,它运行得很好,但当我决定创建一个类来为我获取天气数据时,我遇到了错误。

''

import urllib.request
import json
class weather:
def __init__(self, city, key, URL):
self.city = city
self.key = key
self.URL = "http://api.openweathermap.org/data/2.5/weather?q="

def getTemprature(self,a):
fullURL = str(self.URL+self.city+"&appid="+self.key)
data = urllib.request.urlopen(fullURL).read()
temp = float(json.loads(data)["main"]["temp"])
return temp
city="New Delhi" #default city
apiKey = "54df40e238084fbf095d3540271e48a0"
print(weather.getTemprature(city,apiKey))

''

您的getTemperature函数中有一个拼写错误,您只需要参数'self'。创建天气对象时,应该将city,apiKey传递给初始值设定项,而不是传递给getTemperature函数。

import urllib.request
import json
class weather:
def __init__(self, city, key, URL):
self.city = city
self.key = key
self.URL = "http://api.openweathermap.org/data/2.5/weather?q="
def getTemprature(self):
fullURL = str(self.URL+self.city+"&appid="+self.key)
data = urllib.request.urlopen(fullURL).read()
temp = float(json.loads(data)["main"]["temp"])
return temp
city="New Delhi" #default city
apiKey = "54df40e238084fbf095d3540271e48a0"
weatherNewDelhi = weather(city, apiKey)
print(weatherNewDelhi.getTemprature())

输出:

308.15

相关内容

  • 没有找到相关文章

最新更新