Python值传递给构造函数,变量仍然为空

123*_*php 2 python class

我创建了一个Wetter类的实例,并将一个数字传递给构造函数。变量zip保持为空。为什么?

这是目前url2的值: "https://api.openweathermap.org/data/2.5/weather?zip=,DE&units=metric&appid=xxx"

zip= 没有价值。

我尝试从类中删除变量,因为我将变量声明为空。

import requests
import json

class Wetter:
    key = "xxx" # API KEY von openweathermaps eintragen
    url = "https://api.openweathermap.org/data/2.5/weather?zip="
    parameters = ",DE&units=metric&appid=" + str(key)
    zip = ""
    url2 = "https://api.openweathermap.org/data/2.5/weather?zip=" + str(zip) + ",DE&units=metric&appid=" + str(key)
    data = ""
    json = ""

    def __init__(this, zip):
        this.zip = zip

    def printWeather(this):
        this.data = requests.get(this.url2)
        this.json = json.loads(this.data.text)
        print("Stadt: " + str(this.json["name"]) + "\nTemperatur: " + str(this.json["main"]["temp"]))

if __name__ == "__main__":
    zip = str(input("PLZ eingeben: "))
    obj = Wetter(zip)
    obj.printWeather()
Run Code Online (Sandbox Code Playgroud)

我希望变量将用交付的zip值填充。

mar*_*nus 5

更改url2后需要更新this.zip

def __init__(this, zip):
    this.zip = zip
    this.url2 = "https://api.openweathermap.org/data/2.5/weather?zip=" + str(this.zip) + ",DE&units=metric&appid=" + str(this.key)
Run Code Online (Sandbox Code Playgroud)