python - 我得到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'
在运行此代码时得到。我不知道为什么会发生这种情况,有人可以解释为什么吗?
解决方案
除了对对象的引用(“ ”)之外,该函数.response
不接受任何参数。self
您需要先构造类的实例,然后才能使用该.response()
函数。你需要类似 `my_weatherapi = weatherapi('https://www.some.url.com/', 'some_input_string', 90210)。
此外,错误代码是AttributeError
,不是tributeError
。
总而言之,这其中有很多错误。我建议您先阅读 Python 教程;特别研究定义类以及使用构造函数和类函数。
推荐阅读
- android - 当我通过 android 模拟器通过 ftp 连接并尝试下载文件时出现问题
- python - 从 DataFrame 绘制多条线图
- spring - 我应该如何设计端点以根据 Spring 中的用户角色返回不同的模型
- javascript - 查找数组的最小值和最大值
- javascript - 椭圆之间的Processing.js碰撞检查被破坏
- macos - 为 IHP 安装 nix 时出现 SHA-256 哈希不匹配错误
- python - Winerror 2 系统找不到指定的字段
- ios - SwiftUI 2.0 键盘避免设置滚动条偏移
- django - 插入新记录时,Django Haystack 无法更新索引
- linux - 列出 GCP GAE Linux 中的所有 RSYNCed 文件夹