首页 > 解决方案 > 如何解决此特定代码中的属性错误?

问题描述

尝试运行它时出现以下错误。我用谷歌搜索并没有找到解决方案。有人知道我应该怎么写吗?对不起,我对编程还是很陌生。

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

标签: pythontkinterattributes

解决方案


您的问题已在评论中得到解答,但作为编程新手,查看示例可能会有所帮助。缩进是 Python 中的导入,并且您的convert函数在您的类之外,因为它从类定义中超出了缩进。精简后,您的代码结构应包含convert在以下内容中CurrencyCoverter

class CurrencyConverter():
    def __init__(self, url):
        pass

    def convert(self, from_currency, to_currency, amount): 
        pass

推荐阅读