首页 > 解决方案 > 我得到attributeError:'str'对象在运行此代码时没有属性'zipcode'

问题描述

我的代码:

import requests
class weatherapi:
 def __init__(self,api_url,string,zipcode):
    self.api_url = 'https://api.openweathermap.org/data/2.5/weather?zip=10502,us&appid=50b55ef1602086c74b71f56c6df14996'
    self.input = string
    self.zipcode = zipcode
 def get(self):
    get_weather = requests.get(self.api_url)
    json_weather = get_weather.json()
 def response(self):
    national = requests.get('https://api.openweathermap.org/data/2.5/weather?zip='+self.zipcode+',us&appid=50b55ef1602086c74b71f56c6df14996')
    json_national = national.json()
    kelvin = float(national.json['main']['temp'])
    return str(kelvin)

from weatherapi import weatherapi
def main():
    zipcode = input('Please input your zip code ')
    weatherapi.response(zipcode)

attributeError: 'str' object has no attribute 'zipcode'在运行此代码时得到。我不知道为什么会发生这种情况,有人可以解释为什么吗?

标签: pythonapiclass

解决方案


除了对对象的引用(“ ”)之外,该函数.response不接受任何参数。self

您需要先构造类的实例,然后才能使用该.response()函数。你需要类似 `my_weatherapi = weatherapi('https://www.some.url.com/', 'some_input_string', 90210)。

此外,错误代码是AttributeError,不是tributeError

总而言之,这其中有很多错误。我建议您先阅读 Python 教程;特别研究定义类以及使用构造函数和类函数。


推荐阅读