【问题标题】:Missing 1 required positional argument - 'Self'?缺少 1 个必需的位置参数 - \'Self\'?
【发布时间】:2023-02-06 22:01:22
【问题描述】:

我有某个类的以下方法:

def make_payment(self, cost):

以及主文件中的以下内容:

print(money_machine.make_payment(drink.cost))

为什么要返回这个? (我正在参加一个代码会议,他的代码似乎一切都很好) 类型错误:MoneyMachine.make_payment() 缺少 1 个必需的位置参数:'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)

赚钱机器:

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

【问题讨论】:

  • 你如何实例化money_machine()?我们可以看课吗? -- 我想你没有正确实例化类,在这种情况下 self 不是被调用方法的传递属性
  • 赚钱机器=赚钱机器
  • 是的,你的问题是实例化,请看我的回答。

标签: python-3.x


【解决方案1】:

根据您的 cmets,问题是您没有正确实例化您的类。

总体而言,您的实例化代码应该更像这样:

money_machine = MoneyMachine()

然后调用方法会正确地满足它并且你传递self

【讨论】:

  • 圣母玛利亚。非常感谢!
猜你喜欢
  • 2021-12-15
  • 2021-09-15
  • 2013-07-06
  • 2022-01-05
  • 2017-03-28
  • 2020-01-07
  • 2019-09-26
  • 2017-02-23
相关资源
最近更新 更多