Python의 객체 지향 프로그래밍
Alex Yarosh
Content Quality Analyst @ DataCamp

class BankAccount:
def __init__(self, balance):
self.balance = balance
def withdraw(self, amount):
self.balance -=amount
# BankAccount를 상속한 빈 클래스
class SavingsAccount(BankAccount):
pass
class SavingsAccount(BankAccount): # 이자율 매개변수가 추가된 SavingsAccount 전용 생성자 def __init__(self, balance, interest_rate):# ClassName.__init__()로 부모 생성자 호출 BankAccount.__init__(self, balance) # <--- self는 SavingsAccount이자 BankAccount# 기능 추가 self.interest_rate = interest_rate
Parent.__init__(self, args...)로 부모 생성자를 먼저 실행할 수 있음# 새 생성자로 객체 생성
acct = SavingsAccount(1000, 0.03)
acct.interest_rate
0.03
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)

class CheckingAccount(BankAccount):def __init__(self, balance, limit): BankAccount.__init__(self, balance) self.limit = limitdef deposit(self, amount): self.balance += amountdef withdraw(self, amount, fee=0):if fee <= self.limit: BankAccount.withdraw(self, amount + fee) else: BankAccount.withdraw(self, amount + self.limit)
Parent.method(self, args...)로 호출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의 객체 지향 프로그래밍