You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

运行Python货币转换代码出现'Currency' object has no attribute 'convert'报错求助

问题排查与修复方案

核心报错原因

你触发AttributeError: 'Currency' object has no attribute 'convert'的最直接原因是:你在Currency类中定义的汇率转换方法名为extract_api_result,但调用时使用了不存在的方法名convert。

其他隐藏错误

除了方法名不匹配,你的代码还存在多处会导致后续运行报错的问题:

  • 代码开头的@currency无意义:你没有定义名为currency的装饰器,运行时会直接触发NameError,可以直接删除该行。
  • 实例属性名不匹配:__init__方法中你把汇率数据存到了self.currencies属性,但后续转换逻辑中调用的是self.rates,属性名不一致会触发属性不存在报错。
  • 方法参数顺序与调用不匹配:你定义的转换方法参数顺序是(amount, from_currency, to_currency),但调用时第一个测试用例传参顺序是(from_currency, to_currency, amount),顺序颠倒会导致类型错误。
  • 全局定义的rates = {}没有实际作用,可以直接删除。
  • 存在拼写错误:原代码中inital_amount拼写错误,会导致变量找不到的报错。

修复后可运行代码

import requests
import json

class Currency:
    def __init__(self, url):
        self.data = requests.get(url).json()
        # 统一属性名为rates,和后续调用匹配
        self.rates = self.data['rates']
    # 把方法名改为convert,和调用逻辑匹配,同时调整参数顺序和调用传参对应
    def convert(self, from_currency, to_currency, amount):
        initial_amount = amount
        if from_currency != "EUR":
            amount = amount / self.rates[from_currency]
        if to_currency == "EUR":
            return f"{initial_amount} {from_currency} = {amount:.2f} {to_currency}"
        else:
            return f"{initial_amount} {from_currency} = {amount * self.rates[to_currency]:.2f} {to_currency}"

converter = Currency('https://api.frankfurter.app/latest')

print(converter.convert('INR','USD',100))
print(converter.convert("EUR","USD",1.0))
print(converter.convert("GBP","USD",1.0))
print(converter.convert("CAD","GBP",1.0))
print(converter.convert("CAD","EUR",1.0))

运行效果说明

修复后代码会按要求输出对应汇率转换结果,默认保留两位小数提升可读性。

内容的提问来源于stack exchange,提问作者simple114141

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 23:27:03