상속으로 기능 커스터마이즈

Python 객체 지향 프로그래밍 입문

George Boorman

Curriculum Manager, DataCamp

은행 계좌 클래스 계층

Python 객체 지향 프로그래밍 입문

현재까지 구성

class BankAccount:
    def __init__(self, balance):
       self.balance = balance

    def withdraw(self, amount):
       self.balance -=amount

# BankAccount를 상속한 빈 클래스
class SavingsAccount(BankAccount):
    pass
Python 객체 지향 프로그래밍 입문

생성자 커스터마이즈

class SavingsAccount(BankAccount):    
    # 이자율 인자를 추가한 SavingsAccount 생성자
    def __init__(self, balance, interest_rate):  

# ClassName.__init__()로 부모 생성자 호출 # self는 SavingsAccount이자 BankAccount임 BankAccount.__init__(self, balance)
# 기능 추가 self.interest_rate = interest_rate
  • Parent.__init__(self, args...)로 부모 생성자를 먼저 호출할 수 있음
  • 기능 추가
  • 부모 생성자를 반드시 호출할 필요는 없음
Python 객체 지향 프로그래밍 입문

커스텀 생성자로 객체 생성

# 새 생성자로 객체 생성
acct = SavingsAccount(1000, 0.03)
acct.interest_rate
0.03
Python 객체 지향 프로그래밍 입문

기능 추가

  • 메서드는 평소처럼 추가
  • 부모와 자식 클래스의 데이터를 모두 사용 가능
class SavingsAccount(BankAccount):
    def __init__(self, balance, interest_rate):
        BankAccount.__init__(self, balance)
        self.interest_rate = interest_rate

    # 새 기능
    def compute_interest(self, n_periods=1):
        return self.balance * ( (1 + self.interest_rate) ** n_periods - 1)
Python 객체 지향 프로그래밍 입문

은행 계좌 클래스 계층

Python 객체 지향 프로그래밍 입문

두 번째 자식 클래스 추가

class CheckingAccount(BankAccount):

def __init__(self, balance, limit): BankAccount.__init__(self, balance) # 부모 클래스 생성자 호출 self.limit = limit
def deposit(self, amount): self.balance += amount
def withdraw(self, amount, fee=0): # 새로운 fee 인자
if amount <= self.limit: BankAccount.withdraw(self, amount + fee) else: pass # 조건을 만족하지 않으면 실행되지 않음
Python 객체 지향 프로그래밍 입문
check_acct = CheckingAccount(1000, 25)

# CheckingAccount의 withdraw 호출
check_acct.withdraw(200)

# CheckingAccount의 withdraw 호출 check_acct.withdraw(200, fee=15)
bank_acct = BankAccount(1000)

# BankAccount의 withdraw 호출
bank_acct.withdraw(200)

# 오류 발생 bank_acct.withdraw(200, fee=15)
TypeError: withdraw() got an unexpected
keyword argument 'fee'
  • 다형성 위반
    • 부모/자식 클래스의 메서드가 다름
Python 객체 지향 프로그래밍 입문

연습해 봅시다!

Python 객체 지향 프로그래밍 입문

Preparing Video For Download...