【问题标题】:Getting Attribute Error while creating a class to fetch weather data in python创建类以在python中获取天气数据时出现属性错误
【发布时间】:2020-07-24 00:36:36
【问题描述】:

当我直接执行此方法时它工作正常,但当我决定创建一个将为我获取天气数据的类时出现错误。

'''

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

'''

【问题讨论】:

    标签: python json api openweathermap


    【解决方案1】:

    您的 getTemprature 函数中有错字,您只需要参数“self”。您应该在创建天气对象时将 city、apiKey 传递给初始化程序,而不是传递给 getTemprature 函数。

    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
    

    【讨论】:

    • 不,兄弟,我自己传递了那个额外的参数,否则它会引发另一个错误,指出“预期 1 个参数,但通过了 2 个”
    • 在您的原始代码中,weather.getTemprature(city, apiKey) 不正确,因为您没有使用类初始化程序来创建天气对象。您需要在某个时候通过编写 weather(city, apiKey) 创建一个天气对象,然后对该对象调用 getTemprature() 函数。
    猜你喜欢
    • 2022-11-13
    • 2021-07-07
    • 2014-09-23
    • 1970-01-01
    • 2021-11-09
    • 2022-01-16
    • 2019-05-28
    • 2021-04-17
    • 2021-06-08
    相关资源
    最近更新 更多