Dědičnost tříd

Object-Oriented Programming in Python

Alex Yarosh

Content Quality Analyst @ DataCamp

Znovupoužití kódu

Object-Oriented Programming in Python

Znovupoužití kódu

 

1. Někdo to již udělal

 

  • Moduly jsou vhodné pro pevnou funkcionalitu
  • OOP je vhodné pro přizpůsobení funkcionality

loga několika python balíčků

Object-Oriented Programming in Python

Znovupoužití kódu

 

1. Někdo to již udělal

 

2. DRY: Don't Repeat Yourself

různé prvky GUI

Object-Oriented Programming in Python

Znovupoužití kódu

 

1. Někdo to již udělal

 

2. DRY: Don't Repeat Yourself

nepoužívejte různé prvky GUI

Object-Oriented Programming in Python

Dědičnost

 

$$\Large{\text{Nová třída = Stará třída + rozšíření}}$$

Object-Oriented Programming in Python

třída account

Object-Oriented Programming in Python

savings account zdědí account

Object-Oriented Programming in Python

dvě třídy dědí z account

Object-Oriented Programming in Python

upravená metoda v checking account

Object-Oriented Programming in Python

Implementace dědičnosti tříd

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

class MyChild(MyParent):
   # Do stuff here
  • MyParent: třída, jejíž funkcionalita je rozšiřována/dědí se
  • MyChild: třída, která dědí funkcionalitu a přidává novou
Object-Oriented Programming in Python

Potomek zdědí všechna data rodiče

# Constructor inherited from BankAccount
savings_acct = SavingsAccount(1000)
type(savings_acct)
__main__.SavingsAccount
# Attribute inherited from BankAccount
savings_acct.balance
1000
# Method inherited from BankAccount
savings_acct.withdraw(300)
Object-Oriented Programming in Python

Dědičnost: vztah „je"

SavingsAccount je BankAccount

(případně s dalšími funkcemi)

savings_acct = SavingsAccount(1000)
isinstance(savings_acct, SavingsAccount)
True
isinstance(savings_acct, BankAccount)
True

 

 

acct = BankAccount(500)
isinstance(acct,SavingsAccount)
False
isinstance(acct,BankAccount)
True
Object-Oriented Programming in Python

Pojďme si to procvičit!

Object-Oriented Programming in Python

Preparing Video For Download...