블로그 이미지
조이키트 블로그
아두이노, 라즈베리파이, 반도체 센서/모듈 활용

calendar

1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31

Notice

250x250
2023. 8. 12. 17:35 파이썬
728x90
반응형

프로그램은 Mertagate 클래스와 다음과 같은 세 가지 종류에 해당하는 하위 클래스로 구성한다.

1. 포인트가 없는 고정 금리 대출

2. 포인트가 있는 고정 금리 대출

3. 초기 티져금리로 시작하고 대출 기간 동안 금리가 올라가는 대출

# 대출(Mortgage) 기본 클래스
def findPayment(loan, r, m):
    return loan*((r*(1+r)**m)/((1+r)**m - 1))

class Mortgage(object):
    def __init__(self, loan, annRate, months):
        self.loan = loan
        self.rate = annRate/12.0
        self.months = months
        self.paid = [0.0]
        self.owed = [loan]
        self.payment = findPayment(loan, self.rate, months)
        self.legend = None

    def makePayment(self):
        self.paid.append(self.payment)
        reduction = self.payment - self.owed[-1]*self.rate
        self.owed.append(self.owed[-1] - reduction)

    def getTotalPaid(self):
        return sum(self.paid)
    
    def __str__(self):
        return self.legend

 위의 코드를 보면 추상 클래스 Mertgate가 있다. 이 클래스는 각 하위 클래스에서 함께 사용하는 메소드를 가지고 있지만 직접 인스턴스를 생성하기 위한 클래스는 아니다.

def findPayment(loan, r, m):
    return loan*((r*(1+r)**m)/((1+r)**m - 1))

첫 번째 함수 findPayment는 주어진 기간에 대출을 모두 갚기 위해 은행에 상환해야 할 원금과 이자를 포함한 고정된 월 납입금을 계산해준다.

class Mortgage(object):
    def __init__(self, loan, annRate, months):
        self.loan = loan
        self.rate = annRate/12.0
        self.months = months
        self.paid = [0.0]
        self.owed = [loan]
        self.payment = findPayment(loan, self.rate, months)
        self.legend = None

__init__을 살펴보면 모든 Mertgage의 인스턴스들이 가지고 있는 인스턴스 변수들은 다음과 같다. 초기 대출 금액, 한달 금리, 대출 기간 개월 수, 매월 초에 상환된 금액 리스트(첫 번째 달에는 아무 금액도 상환하지 않기 때문에 리스트는 0.0으로 시작한다.) 매월 초에 미결제된 잔액의 리스트, 매월 내는 납입금(findPayment 함수가 반환하는 값으로 초기화 된다.) 모든 Mertgate의 하위 클래스들은 __init__은 제일 먼저 Mertgage.__init__을 호출하고 그 다음에 self.legend를 각각 하위 클래스에 쓰여져 있는 설명대로 알맞게 초기화해야 한다.

    def makePayment(self):
        self.paid.append(self.payment)
        reduction = self.payment - self.owed[-1]*self.rate
        self.owed.append(self.owed[-1] - reduction)

makePayment 메소드는 대출 납입금을 기록하기 위한 용도이다. 각 납입금은 대출 잔액으로 인한 이자를 포함한 것이며, 그 나머지는 대출 잔금을 줄여 나간다. 이것 때문에 makePayment는 self.paid와 self.owed이 두 값 모두를 갱신한다.

    def getTotalPaid(self):
        return sum(self.paid)

getTotalPaid 메소드는 일련의 숫자들의 합을 반환해주는 파이썬 내장 함수 sum을 사용한다. 만약 숫자가 아닌 값이 있다면 예의를 발생한다.

다음 코드는 두 종류의 대출의 클래스를 구현하고 있다. 각 클래스는 __init__ 함수를 올버라이드하고 있으며 Mortgage에서 또 다른 세 가지 메소드를 상속받고 있다.

# 고정 금리 대출 클래스
class Fixed(Mortgage):
    def __init__(self, loan, r, months):
        Mortgage.__init__(self, loan, r, months)
        self.legend = 'Fixed, ' + str(r*100) + '%'

class FixedWithPts(Mortgage):
    def __init__(self, loan, r, months, pts):
        Mortgage.__init__(self, loan, r, months)
        self.pts = pts
        self.paid = [loan*(pts/100.0)]
        self.legend = 'Fixed, ' + str(r*100) + '%, '\
        + str(pts) + ' points'

 다음은 Mortgage의 세번쨰 하위 클래스이다. TwoRate 클래스는 마치 두 개의 다른 금리를 가지고 있는 대출을 병합한 것처럼 다루고 있다. self.paid가 0.0으로 초기화되어 있기 때문에 지불한 횟수보다 하나 더 많은 값을 가지고 있다. 때문에 makePayment는 len(self.paid)를 self.teaserMonths + 1과 비교하고 있는 것이다.

# 티져금리와 대출
class TwoRate(Mortgage):
    def __init__(self, loan, r, months, teaserRate, teaserMonths):
        Mortgage.__init__(self, loan, teaserRate, months)
        self.teaserMonths = teaserMonths
        self.teaserRate = teaserRate
        self.nextRate = r/12.0
        self.legend = str(teaserRate*100)\
        + '% for' + str(self.teaserMonths)\
        + 'months, then' + str(r*100) + '%'

    def makePayment(self):
        if len(self.paid) == self.teaserMonths + 1:
            self.rate = self.nextRate
            self.payment = findPayment(self.owed[-1], self.rate, self.months - self.teaserMonths)
        Mortgage.makePayment(self)

다음은 세 종류의 대출 모두의 비용을 샘플 매개변수로 계산 후 출력해주는 함수는 함수이다. 각 종류마다 클래스들을 생성한 후, 주어진 햇수로 매달 상환해야 할 금액을 계산한다. 끝으로 각 대출마다 총 상환액을 출력한다. 

# 대출 금액 계산하기
def compareMortgages(amt, years, fixedRate, pts, ptsRate, varRate1, varRate2, varMonths):
    totMonths = years*12
    fixed1 = Fixed(amt, fixedRate, totMonths)
    fixed2 = FixedWithPts(amt, ptsRate, totMonths, pts)
    twoRate = TwoRate(amt, varRate2, totMonths, varRate1, varMonths)
    morts = [fixed1, fixed2, twoRate]
    for m in range(totMonths):
        for mort in morts:
            mort.makePayment()
        for m in morts:
            print(m)
            print('Total payment = $' + str(int(m.getTotalPaid())))

출력 결과

Fixed, 7.000000000000001%
Total payment = $479017
Fixed, 5.0%, 3.25 points
Total payment = $393011
4.5% for 48 months, then 9.5%
Total payment = $551444
728x90
반응형

'파이썬' 카테고리의 다른 글

파이썬 (합병 정렬과 이름 리스트 정렬하기)  (0) 2023.08.28
(파이썬) 점근 표기법  (0) 2023.08.16
(파이썬) Grades 클래스  (0) 2023.08.12
(파이썬) 상속/Inheritance  (0) 2023.08.09
(파이썬) Person 클래스  (0) 2023.08.09
posted by 조이키트 블로그