Pengantar Pemrograman Berorientasi Objek di Python
George Boorman
Curriculum Manager, DataCamp

class BankAccount:
def __init__(self, balance):
self.balance = balance
def withdraw(self, amount):
self.balance -=amount
# Kelas kosong yang mewarisi dari BankAccount
class SavingsAccount(BankAccount):
pass
class SavingsAccount(BankAccount): # Konstruktor SavingsAccount dengan argumen tambahan def __init__(self, balance, interest_rate):# Panggil konstruktor induk dengan ClassName.__init__() # self adalah SavingsAccount sekaligus BankAccount BankAccount.__init__(self, balance)# Tambahkan fungsionalitas self.interest_rate = interest_rate
Parent.__init__(self, args...)# Bangun objek dengan konstruktor baru
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
# Fungsionalitas baru
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) # Panggil konstruktor ParentClass self.limit = limitdef deposit(self, amount): self.balance += amountdef withdraw(self, amount, fee=0): # Argumen fee baruif amount <= self.limit: BankAccount.withdraw(self, amount + fee) else: pass # Tidak dijalankan jika kondisi tidak terpenuhi
check_acct = CheckingAccount(1000, 25) # Akan memanggil withdraw dari CheckingAccount check_acct.withdraw(200)# Akan memanggil withdraw dari CheckingAccount check_acct.withdraw(200, fee=15)
bank_acct = BankAccount(1000) # Akan memanggil withdraw dari BankAccount bank_acct.withdraw(200)# Akan menghasilkan error bank_acct.withdraw(200, fee=15)
TypeError: withdraw() got an unexpected
keyword argument 'fee'
Pengantar Pemrograman Berorientasi Objek di Python