Introducción a la programación orientada a objetos en Python
George Boorman
Curriculum Manager, DataCamp

class BankAccount:
def __init__(self, balance):
self.balance = balance
def withdraw(self, amount):
self.balance -=amount
# Clase vacía que hereda de BankAccount
class SavingsAccount(BankAccount):
pass
class SavingsAccount(BankAccount): # Constructor de SavingsAccount con un argumento adicional def __init__(self, balance, interest_rate):# Llama al constructor del padre con ClassName.__init__() # self es SavingsAccount y también BankAccount BankAccount.__init__(self, balance)# Añade más funcionalidad self.interest_rate = interest_rate
Parent.__init__(self, args...)# Construye el objeto con el nuevo constructor
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
# Nueva funcionalidad
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) # Llama al constructor de la clase padre self.limit = limitdef deposit(self, amount): self.balance += amountdef withdraw(self, amount, fee=0): # Nuevo argumento feeif amount <= self.limit: BankAccount.withdraw(self, amount + fee) else: pass # No se ejecuta si no se cumple la condición
check_acct = CheckingAccount(1000, 25) # Llamará a withdraw de CheckingAccount check_acct.withdraw(200)# Llamará a withdraw de CheckingAccount check_acct.withdraw(200, fee=15)
bank_acct = BankAccount(1000) # Llamará a withdraw de BankAccount bank_acct.withdraw(200)# Producirá un error bank_acct.withdraw(200, fee=15)
TypeError: withdraw() got an unexpected
keyword argument 'fee'
Introducción a la programación orientada a objetos en Python