繁体   English   中英

从外部读取湿度数据的属性错误 API API

[英]Attribute Error API for reading humidity data from external API

我想从 API 读取湿度数据,但我一直收到属性错误。 任何人都可以提供帮助,我是编码和 python 的新手。

错误:

Traceback (most recent call last):
  File "C:\Users...HidenForPrivacy", line 27, in <module>
    test.current_humidity()
  File "C:\Users...HidenForPrivacy", line 20, in current_humidity
    response = requests.get(self.url)
AttributeError: 'humidity' object has no attribute 'url'


    
import requests
import json
class humidity():
    def init(self,humidity, url):
        self.humidity = humidity
        self.api_key = "hiddenforprivacy"
        self.lat = "53.5502"
        self.lon = "9.9920"
        self.url = url

    def current_humidity(self):
        response = requests.get(self.url)
        data = json.loads(response.text)
        self.url = "https://api.openweathermap.org/data/2.5/onecall?lat=%s&lon=%s&appid=%s&units=metric" % (self.lat, self.lon, self.api_key)
        self.humidity = data["current"]["humidity"]
        print(humidity)

test = humidity()
test.current_humidity()

问题是您尚未为 self.url 设置任何值

当你调用test = humidity()时,你调用的不是init(self, humidity, url)方法,而是空的__init__(self)方法(Python 中的构造函数称为__init__ )。 所以没有设置 url。

在您的代码中,您确实在第 22 行中设置了 url self.url = "https://api.openweath... ,但这发生在您已经调用response = requests.get(self.url)之后。

一种解决方案可能是在response = requests.get(self.url)之前放置self.url = "https://api.openweath...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM