【问题标题】:I have a problem with classes and inputs in Python我对 Python 中的类和输入有疑问
【发布时间】:2020-03-25 15:59:03
【问题描述】:

我刚开始学习课程,正在尝试构建一个计算器 这告诉人们他们需要给服务员多少小费作为一个小项目 但不是输入我自己的信息,我希望用户自己做,这样它就可以满足他的需要。 现在我认为我构建它是正确的,计算机接受输入但是当我尝试调用时 return_answer() 函数我收到一条错误消息: AttributeError:tip_calculator 对象没有属性“return_answer” 有人可以向我解释我做错了什么以及如何解决吗? 在此先感谢:)

class tip_calculator:
    def __init__(self,bill,amount_of_diners,precent):
        self.bill = bill
        self.amount_of_diners = amount_of_diners
        self.precent = precent

        def return_answer(self):
            print("The amount you need to pay is: ", precent * bill / amount_of_diners ** bill * 1000)

calc = tip_calculator(int(input("What was the bill?: ")), 
                      int(input("With how many people did you eat?: ")),
                      int(input("what '%' do you want to give the waiter?: ")))

calc.return_answer()

【问题讨论】:

    标签: python-3.x class oop


    【解决方案1】:

    问题在于缩进:

    class tip_calculator:
        def __init__(self, bill, amount_of_diners, precent):
            self.bill = bill
            self.amount_of_diners = amount_of_diners
            self.precent = precent
    
        def return_answer(self):
            print(
                "The amount you need to pay is: ",
                self.precent * self.bill / self.amount_of_diners ** self.bill * 1000,
            )
    
    
    calc = tip_calculator(
        int(input("What was the bill?: ")),
        int(input("With how many people did you eat?: ")),
        int(input("what '%' do you want to give the waiter?: ")),
    )
    
    calc.return_answer()
    

    您的 return_answer 方法在初始化程序 (__init__) 中缩进错误。此外,在您的 return_answer 中,当您想要访问类成员(如字段 billamount_of_dinerspercent)时,您需要使用 self 进行操作,因为它们是您的类的成员而不是局部变量你的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-20
      • 2022-12-13
      • 2018-08-07
      • 1970-01-01
      • 2021-09-08
      • 1970-01-01
      相关资源
      最近更新 更多