我刚刚开始学习课程,并试图构建一个计算器 告诉人们作为小项目他们需要给小费多少钱 但是我不想让我自己输入信息,而是希望用户自己动手做,以便适合他的需要。 现在我认为我没做错,计算机可以接受输入,但是当我尝试打电话时 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()
答案 0 :(得分:2)
问题在于缩进:
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
中,当您想访问类成员,例如字段bill
,amount_of_diners
和percent
时,您需要使用self
进行操作,因为它们是您的类的成员,而不是方法的局部变量。