Налаштування функціональності через наслідування

Об'єктноорієнтоване програмування в Python

Alex Yarosh

Content Quality Analyst @ DataCamp

ієрархія класів облікових записів

Об'єктноорієнтоване програмування в Python

Що маємо наразі

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

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

# Empty class inherited from BankAccount
class SavingsAccount(BankAccount):
    pass
Об'єктноорієнтоване програмування в Python

Налаштування конструкторів

class SavingsAccount(BankAccount):    

    # Constructor specifically for SavingsAccount with an additional parameter
    def __init__(self, balance, interest_rate):  

# Call the parent constructor using ClassName.__init__() BankAccount.__init__(self, balance) # <--- self is a SavingsAccount but also a BankAccount
# Add more functionality self.interest_rate = interest_rate
  • Можна спочатку викликати конструктор батьківського класу через Parent.__init__(self, args...)
  • Додайте нову функціональність
  • Не обов'язково викликати конструктори батьківського класу
Об'єктноорієнтоване програмування в Python

Створення об'єктів із налаштованим конструктором

# Construct the object using the new constructor
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

  # New functionality
  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):
if fee <= self.limit: BankAccount.withdraw(self, amount + fee) else: BankAccount.withdraw(self, amount + self.limit)
  • Можна змінити сигнатуру (додати параметри)
  • Використовуйте Parent.method(self, args...), щоб викликати метод батьківського класу
Об'єктноорієнтоване програмування в Python
check_acct = CheckingAccount(1000, 25)

# Will call withdraw from CheckingAccount
check_acct.withdraw(200)
# Will call withdraw from CheckingAccount
check_acct.withdraw(200, fee=15)
bank_acct = BankAccount(1000)

# Will call withdraw from BankAccount
bank_acct.withdraw(200)
# Will produce an error
bank_acct.withdraw(200, fee=15)
TypeError: withdraw() got an unexpected
 keyword argument 'fee'
Об'єктноорієнтоване програмування в Python

Давайте потренуємось!

Об'єктноорієнтоване програмування в Python

Preparing Video For Download...