'Attribute Error API for reading humidity data from external API

I want to read to humidity data from the API but I keep getting an atribute error. Anybody can help, I am new to coding and python.

Error:

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


Solution 1:[1]

The problem is that you have not yet set any value to self.url

When you call test = humidity(), you do not call the init(self, humidity, url) method, but the empty __init__(self) method (the constructor in Python is called __init__). So there the url is not set.

In your code you do set the url in line 22 self.url = "https://api.openweath..., but that happens after you already called response = requests.get(self.url).

One solution might be to put the line self.url = "https://api.openweath... before response = requests.get(self.url)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ziming Song