12.19. OOP Inheritance Inherit

  • Child inherits all fields and methods from parent

12.19.1. Methods

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

12.19.2. Attributes

>>> class Parent:
...     def __init__(self):
...         self.firstname = 'Mark'
...         self.lastname = 'Watney'
>>>
>>>
>>> class Child(Parent):
...     pass
>>>
>>>
>>> obj = Child()
>>> vars(obj)
{'firstname': 'Mark', 'lastname': 'Watney'}

12.19.3. Use Case - 0x01

>>> class Person:
...     def __init__(self):
...         self.firstname = 'Mark'
...         self.lastname = 'Watney'
...
...     def say_hello(self):
...         return 'hello'
>>>
>>>
>>> class Astronaut(Person):
...     pass
>>>
>>> class Cosmonaut(Person):
...     pass

12.19.4. Use Case - 0x02

>>> 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')

12.19.5. References

1

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

12.19.6. Assignments

Code 12.21. 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