python - 如何解决此特定代码中的属性错误?
问题描述
尝试运行它时出现以下错误。我用谷歌搜索并没有找到解决方案。有人知道我应该怎么写吗?对不起,我对编程还是很陌生。
AttributeError Traceback (most recent call last)
<ipython-input-7-50d6838a5474> in <module>
1 url = 'https://api.exchangerate-api.com/v4/latest/USD'
2 converter = CurrencyConverter(url)
----> 3 print(converter.convert('INR','USD',100))
AttributeError: 'CurrencyConverter' object has no attribute 'convert'
这是代码
import requests
from tkinter import *
import tkinter as tk
from tkinter import ttk
class CurrencyConverter():
def __init__(self,url):
self.data= requests.get(url).json()
self.currencies = self.data['rates']
def convert(self, from_currency, to_currency, amount):
initial_amount = amount
#first convert it into USD if it is not in USD.
# because our base currency is USD
if from_currency != 'USD' :
amount = amount / self.currencies[from_currency]
# limiting the precision to 4 decimal places
amount = round(amount * self.currencies[to_currency], 4)
return amount
url = 'https://api.exchangerate-api.com/v4/latest/USD'
converter = CurrencyConverter(url)
print(converter.convert('INR','USD',100))
解决方案
您的问题已在评论中得到解答,但作为编程新手,查看示例可能会有所帮助。缩进是 Python 中的导入,并且您的convert
函数在您的类之外,因为它从类定义中超出了缩进。精简后,您的代码结构应包含convert
在以下内容中CurrencyCoverter
:
class CurrencyConverter():
def __init__(self, url):
pass
def convert(self, from_currency, to_currency, amount):
pass
推荐阅读
- vue.js - Vueutify 导航抽屉 - 更改背景图像
- module - 为什么 Utop 对待这个 Ocaml 代码的方式不同
- swift - Swift - 在嵌入在选项卡栏中的导航控制器中重置 vc
- python - 在 Flask 中重定向页面时遇到问题
- javascript - 将 FullCalendar 集成到 Apache Royale
- linux - 使用什么系统调用通过 Internet 发送数据?
- scala - 如何检查空 JSON
- keras - tf.keras HDF5 模型和 Keras HDF5 模型
- php - 在 xampp localhost 不起作用,本地网络 ip 适用于项目
- terraform - 使用 terraform 在 digitalOcean 中带液滴的体积附件