13.6. OOP Inheritance

13.6.1. Rationale

  • Child inherits all fields and methods from parent

  • Used to avoid code duplication

parent
superclass
base class

Class from other classes inherits

child
subclass

Class which inherits from parent

inherit
derive

Class takes attributes and methods from parent.

13.6.2. Methods

>>> class Parent:
...     def say_hello(self):
...         return 'Hello'
>>>
>>> class Child(Parent):
...     pass
>>>
>>>
>>> obj = Child()
>>> obj.say_hello()
'Hello'

13.6.3. Attributes

>>> class Person:
...     firstname: str
...     lastname: str
...
...     def __init__(self, firstname, lastname):
...         self.firstname = firstname
...         self.lastname = lastname
>>>
>>>
>>> class Astronaut(Person):
...     pass
>>>
>>> class Cosmonaut(Person):
...     pass
>>>
>>>
>>> mark = Astronaut('Mark', 'Watney')
>>> ivan = Cosmonaut('Ivan', 'Ivanovic')

13.6.4. Use Case - Iris

>>> class Iris:
...     sepal_length: float
...     sepal_width: float
...     petal_length: float
...     petal_width: float
...     species: str
...
...     def __init__(self, sepal_length, sepal_width,
...                  petal_length, petal_width, species):
...         self.sepal_length = sepal_length
...         self.sepal_width = sepal_width
...         self.petal_length = petal_length
...         self.petal_width = petal_width
...         self.species = species
>>>
>>>
>>> class Setosa(Iris):
...     pass
>>>
>>> class Versicolor(Iris):
...     pass
>>>
>>> class Virginica(Iris):
...     pass
>>>
>>>
>>> setosa = Setosa(
...     sepal_length=5.1,
...     sepal_width=3.5,
...     petal_length=1.4,
...     petal_width=0.2,
...     species='setosa')

13.6.5. References

1

https://www.youtube.com/watch?v=EiOglTERPEo

13.6.6. Assignments

Code 13.11. Solution
"""
* Assignment: OOP Inheritance Simple
* Required: yes
* Complexity: easy
* Lines of code: 4 lines
* Time: 3 min

English:
    1. Create class `Woman` which inherits from `Venus`
    2. Create class `Man` which inherits from `Mars`
    3. Run doctests - all must succeed

Polish:
    1. Stwórz klasę `Woman`, która dziedziczy po `Venus`
    2. Stwórz klasę `Man`, która dziedziczy po `Mars`
    3. Uruchom doctesty - wszystkie muszą się powieść

Tests:
    >>> import sys; sys.tracebacklimit = 0
    >>> from inspect import isclass

    >>> assert isclass(Venus)
    >>> assert isclass(Woman)
    >>> assert isclass(Mars)
    >>> assert isclass(Man)
    >>> assert issubclass(Woman, Venus)
    >>> assert issubclass(Man, Mars)
"""


class Venus:
    pass


class Mars:
    pass