简体   繁体   English

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

[英]Python Value passed to constructor, Variable still empty

I created an instance of Wetter class and passed a number to the constructor. 我创建了Wetter类的实例,并向构造函数传递了一个数字。 Variable zip stays empty. 可变的zip保持为空。 Why? 为什么?

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

zip= has no value. zip=没有价值。

I tried deleting the variable from the class, because I declared the variable as empty. 我尝试从类中删除变量,因为我将变量声明为空。

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

I expect the variable to be filled with the delivered zip value. 我希望变量将用交付的zip值填充。

You need to update url2 after this.zip was changed: 您需要更新url2this.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)

It's a simple mistake Instead of doing 这是一个简单的错误

    zip = ""

Try doing 尝试做

    this.zip = ""

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

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