16.7. OOP Init Define

  • __init__() - initializer method

  • It's a first method run after object is initiated

  • All classes has default __init__()

constructor

Method called at object instantiation used to create object. Constructor is called on not fully initialized object and hence do not have access to object methods. Constructor should return None.

initializer

Method called at object instantiation used to fill empty object with values. Initializer is called upon object initialization and hence can modify object and use its methods. Initializer should return None.

16.7.1. Without Arguments

Initializer method without arguments:

>>> class User:
...     def __init__(self):
...         print('Hello')
>>>
>>>
>>> mark = User()
Hello

16.7.2. Required Parameters

>>> class User:
...     def __init__(self, firstname, lastname):
...         print(f'Hello {firstname} {lastname}')
>>>
>>>
>>> mark = User()
Traceback (most recent call last):
TypeError: User.__init__() missing 2 required positional arguments: 'firstname' and 'lastname'
>>> class User:
...     def __init__(self, firstname, lastname):
...         print(f'Hello {firstname} {lastname}')
>>>
>>>
>>> mark = User('Mark', 'Watney')
Hello Mark Watney
>>>
>>> mark = User(firstname='Mark', lastname='Watney')
Hello Mark Watney

16.7.3. Optional Parameters

>>> class User:
...     def __init__(self, firstname=None, lastname=None):
...         print(f'Hello {firstname} {lastname}')
>>>
>>>
>>> mark = User('Mark', 'Watney')
Hello Mark Watney
>>>
>>> mark = User('Mark')
Hello Mark None
>>>
>>> mark = User()
Hello None None

16.7.4. Assignments

Code 16.8. Solution
"""
* Assignment: OOP Init Define
* Type: class assignment
* Complexity: easy
* Lines of code: 3 lines
* Time: 2 min

English:
    1. Create one class `Hello`
    2. At initialization instance print `hello world`
    3. Do not store any values
    4. Run doctests - all must succeed

Polish:
    1. Stwórz jedną klasę `Hello`
    2. Przy inicjalizacji instancja wypisuje `hello world`
    3. Nie przechowuj żadnych informacji
    4. Uruchom doctesty - wszystkie muszą się powieść

Tests:
    >>> import sys; sys.tracebacklimit = 0

    >>> result = Hello()
    hello world
    >>> vars(result)
    {}
"""


Code 16.9. Solution
"""
* Assignment: OOP Init Define
* Type: class assignment
* Complexity: easy
* Lines of code: 3 lines
* Time: 2 min

English:
    1. Create one class `Echo`
    2. Value `text` must be passed at the initialization
    3. At initialization instance print `text`
    4. Do not store values in the instances (only print on instance creation)
    5. Do not use `@dataclass`
    6. Run doctests - all must succeed

Polish:
    1. Stwórz jedną klasę `Echo`
    2. Wartość `text` maja być podawana przy inicjalizacji
    3. Przy inicjalizacji instancja wypisuje `text`
    4. Nie przechowuj informacji w instancjach
       (tylko wypisz przy inicjalizacji)
    5. Nie używaj `@dataclass`
    6. Uruchom doctesty - wszystkie muszą się powieść

Tests:
    >>> import sys; sys.tracebacklimit = 0

    >>> _ = Echo('hello')
    hello
    >>> _ = Echo('world')
    world
    >>> result = Echo('Test')
    Test
    >>> vars(result)
    {}
"""


Code 16.10. Solution
"""
* Assignment: OOP Init Define
* Type: class assignment
* Complexity: easy
* Lines of code: 4 lines
* Time: 5 min

English:
    1. Modify code below
    2. Define `__init__()` method in both classes
    3. Signature should reflect class attributes
    4. Method `__init__()` raises exception `NotImplementedError`
    5. Run doctests - all must succeed

Polish:
    1. Zmodyfikuj kod poniżej
    2. Zdefiniuj metodę `__init__()` w obu klasach
    3. Sygnaturą powinna odpowiadać atrybutom klasy
    4. Metoda `__init__()` ma podnosić wyjątek `NotImplementedError`
    5. Uruchom doctesty - wszystkie muszą się powieść

Tests:
    >>> import sys; sys.tracebacklimit = 0
    >>> from inspect import ismethod, signature

    >>> mark = Astronaut('Mark', 'USA', '1969-07-21')
    Traceback (most recent call last):
    NotImplementedError

    >>> nasa = SpaceAgency('Nasa', 'USA', '1969-07-21')
    Traceback (most recent call last):
    NotImplementedError

    >>> signature(Astronaut.__init__)
    <Signature (self, name, country, date)>
    >>> signature(SpaceAgency.__init__)
    <Signature (self, name, country, date)>
"""


class Astronaut:
    name: str
    country: str
    date: str


class SpaceAgency:
    name: str
    country: str
    date: str