在python中练习OOP学徒
我正在用Python学习和实践OOP,在麻省理工学院的课程中做一些练习。我从这一部分开始,它将计算支付房屋首期所需的月数。我得到这个错误:“House\u hunting”对象没有属性“number\u of\u months”在python中练习OOP学徒,python,oop,Python,Oop,我正在用Python学习和实践OOP,在麻省理工学院的课程中做一些练习。我从这一部分开始,它将计算支付房屋首期所需的月数。我得到这个错误:“House\u hunting”对象没有属性“number\u of\u months” class House_hunting: def __init__(self, total_cost, portion_saved, annual_salary): self.total_cost = (total_cost)
class House_hunting:
def __init__(self, total_cost, portion_saved, annual_salary):
self.total_cost = (total_cost)
self.portion_saved = float(portion_saved)
self.annual_salary = (annual_salary)
portion_down_payment = (self.total_cost)*0.25
currentsavings = 0
r = 0.04
monthly_salary = (self.annual_salary)/12
number_of_months = 0
if currentsavings < portion_down_payment:
savings = currentsavings*r/12 + monthly_salary*float(self.portion_saved)
number_of_months = number_of_months + 1
else:
print(number_of_months)
a = House_hunting(1000000, 0.10, 120000)
print(a.number_of_months())
class House\u狩猎:
定义初始(自身、总成本、节省部分、年薪):
self.total_cost=(total_cost)
self.partment\u saved=浮动(partment\u saved)
self.年薪=(年薪)
部分首付款=(自付总成本)*0.25
当前节省=0
r=0.04
月薪=(个人年薪)/12
月数=0
如果当前储蓄<部分首付款:
储蓄=当前储蓄*r/12+月薪*浮动(自存部分)
月数=月数+1
其他:
打印(月数)
a=房屋狩猎(1000000,0.101200000)
打印(a.月数()
您的对象没有错误消息中所述的“月数”属性。目前,您的类只有一个在初始化中使用的变量,但随后被丢弃。为了保存计算出的月数,您应该调整代码,所以看起来有点像这样
class House\u狩猎:
定义初始(自身、总成本、节省部分、年薪):
self.total_cost=(total_cost)
self.partment\u saved=浮动(partment\u saved)
self.年薪=(年薪)
部分首付款=(自付总成本)*0.25
当前节省=0
r=0.04
月薪=(个人年薪)/12
self.number\u的月数=0
如果当前储蓄<部分首付款:
储蓄=当前储蓄*r/12+月薪*浮动(自存部分)
self.number月数=self.number月数+1
其他:
打印(自身月数)
a=房屋狩猎(1000000,0.101200000)
打印(a.月数)
还请注意,
()
是不需要的,因为您直接访问属性,而不调用函数。您在\uu init\uuuuuuuuu
内部有一个名为的局部变量,但它不是您的房屋搜索对象的属性(或方法)。谢谢。现在开始工作了!尽管如此,我仍然有一个循环的问题,bcz我得到一个月的首期付款。所以,我正在努力解决这个问题。如果你在我的代码中看到另一个错误,如果你告诉我,我会原谅你的。