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

Python类方法调用报错:缺少必要位置参数'cost'排查

问题排查:调用MoneyMachine.make_payment()触发TypeError

调用MoneyMachine类的make_payment方法时触发TypeError,提示“MoneyMachine.make_payment() missing 1 required positional argument: 'cost'”,相关代码如下:

主文件代码

from menu import Menu, MenuItem
from coffee_maker import CoffeeMaker
from money_machine import MoneyMachine

"""1print report
2check resources sufficies
process coins 
check transaction successful
make coffee
"""
coffee_maker = CoffeeMaker()
menu = Menu()
money_machine = MoneyMachine  # 问题所在行

is_on = True
while is_on:

    print(menu.get_items())
    order = input("your order: ")
    if order == 'off':
        is_on = False
    elif order == "report":
        coffee_maker.report()
    else:
        drink = menu.find_drink(order)
        if coffee_maker.is_resource_sufficient(drink):
            if money_machine.make_payment(drink.cost):
                coffee_maker.make_coffee(drink)

MoneyMachine类代码

class MoneyMachine:

    CURRENCY = "$"

    COIN_VALUES = {
        "quarters": 0.25,
        "dimes": 0.10,
        "nickles": 0.05,
        "pennies": 0.01
    }

    def __init__(self):
        self.profit = 0
        self.money_received = 0

    def report(self):
        """Prints the current profit"""
        print(f"Money: {self.CURRENCY}{self.profit}")

    def process_coins(self):
        """Returns the total calculated from coins inserted."""
        print("Please insert coins.")
        for coin in self.COIN_VALUES:
            self.money_received += int(input(f"How many {coin}?: ") * self.COIN_VALUES[coin])
        return self.money_received

    def make_payment(self, cost):
        """Returns True when payment is accepted, or False if insufficient."""
        print(self.money_received)
        self.process_coins()
        if self.money_received >= cost:
            change = round(self.money_received - cost, 2)
            print(f"Here is {self.CURRENCY}{change} in change.")
            self.profit += cost
            self.money_received = 0
            return True
        else:
            print("Sorry that's not enough money. Money refunded.")
            self.money_received = 0
            return False

错误原因

  • 核心问题:未实例化MoneyMachine类
    主文件中money_machine = MoneyMachine只是将类本身赋值给变量,而非创建类的实例。当直接通过类调用实例方法时,Python不会自动传入self参数,此时你只传入了drink.cost,相当于只给方法传了一个参数,但make_payment需要self和cost两个参数,因此报错提示缺少cost(实际是缺少self,但报错信息会显示下一个必填参数)。

修复方案

将主文件中的money_machine = MoneyMachine修改为:

money_machine = MoneyMachine()

这行代码会创建MoneyMachine类的实例,之后调用money_machine.make_payment(drink.cost)时,Python会自动将实例作为self参数传入方法,参数数量匹配后即可正常运行。

额外小问题修复

MoneyMachine类的process_coins方法中存在逻辑错误:

# 原错误代码
self.money_received += int(input(f"How many {coin}?: ") * self.COIN_VALUES[coin])

应该先将输入转换为整数,再乘以硬币面值,否则会先执行字符串乘浮点数的操作,导致错误或逻辑异常,修正为:

self.money_received += int(input(f"How many {coin}?: ")) * self.COIN_VALUES[coin]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 19:02:12