TheEWL TheEWL - 6 months ago 24
Python Question

Python Class - Methods

So I am trying to create a program that has a class called "Loan" which calculates the monthly payment and total payment of a car with data fields. I'm guessing that my error is caused by having a method ( getMonthlyPayment() ) in the method ( getTotalPayment ). How do I put a method inside a method? Or is there another solution to my problem?

Thanks!

My error is:


Traceback (most recent call last):
File "C:\Users\ericl_000\Desktop\Python\HW 5 ( Python ).py", line 38, in <module>
main()
File "C:\Users\ericl_000\Desktop\Python\HW 5 ( Python ).py", line 37, in main
print("The total payment is ", loan.getTotalPayment())
File "C:\Users\ericl_000\Desktop\Python\HW 5 ( Python ).py", line 27, in getTotalPayment
return getMonthlyPayment * self.__NumYearsLoans * 12
NameError: name 'getMonthlyPayment' is not defined
>>>



class Loan:
def __init__(self, AnnIntRate = 1.0, NumYearsLoans = 1.0, LoanAmt = 1.0, BoName = " "):
self.__AnnIntRate = AnnIntRate
self.__NumYearsLoans = NumYearsLoans
self.__LoanAmt = LoanAmt
self.__BoName = BoName
def getAnnIntRate(self):
return self.__AnnIntRate
def getNumYearsLoans(self):
return self.__NumYearsLoans
def getLoanAmt(self):
return self.__LoanAmt
def getBoName(self):
return self.__BoName
def setAnnIntRate(self,AnnIntRate):
self.__AnnIntRate = AnnIntRate
def setNumYearsLoans(self,NumYearsLoans):
self.__NumYearsLoans = NumYearsLoans
def setLoanAmt(self,LoanAmt):
self.__LoanAmt = LoanAmt
def setBoName(self,BoName):
self.__BoName = BoName
def getMonthlyPayment(self):
monthlyIntRate = self.__AnnIntRate / 1200
return self.__LoanAmt * monthlyIntRate / ( 1 - ( 1 / ( 1 + monthlyIntRate) ** ( self.__NumYearsLoans * 12 )))
def getTotalPayment(self):
return getMonthlyPayment() * self.__NumYearsLoans * 12
def main():
YearlyIntRate = float(input("Enter yearly interest rate, for example, 7.25: "))
NumOfYears = float(input("Enter number of years as an integer: "))
LoanAmount = float(input("Enter loan amount, for example, 120000.95: "))
BorrowerName = input("Enter a borrow's name: ")
loan = Loan(YearlyIntRate,NumOfYears,LoanAmount,BorrowerName)
print("The loan is for ", loan.getBoName())
print("The monthly payment is ", loan.getMonthlyPayment())
print("The total payment is ", loan.getTotalPayment())
main()

Answer

Just like accessing members, you need to prepend all accesses to methods with self..

Change getTotalPayment() to

return self.getMonthlyPayment() * self.__NumYearsLoans * 12

Also, take a look at property to make getters and setters less painful. However, most of the time, you shouldn't even be defining getters and setters in Python. Private-ness is not usually treated as a concept in idiomatic Python.