12.7. OOP Attribute Initialize

12.7.1. Rationale

  • 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.

12.7.2. Syntax

>>> class MyClass:
...     def __init__(self, required, optional=None):
...         pass
>>>
>>>
>>> myobj = MyClass('myvalue')

12.7.3. Initializer Method Without Arguments

Initializer method without arguments:

>>> class Astronaut:
...     def __init__(self):
...         print('Hello')
>>>
>>>
>>> astro = Astronaut()
Hello

12.7.4. Initializer Method With Arguments

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

12.7.5. Assignments

Code 12.8. Solution
"""
* Assignment: OOP Init Print
* Required: yes
* Complexity: easy
* Lines of code: 3 lines
* Time: 3 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 12.9. Solution
"""
* Assignment: OOP Init Model
* Required: yes
* Complexity: easy
* Lines of code: 12 lines
* Time: 8 min

English:
    1. Modify code below
    2. Values must be passed at the initialization
    3. Create instances of a first class using positional arguments
    4. Create instances of a second class using keyword arguments
    5. Run doctests - all must succeed

Polish:
    1. Zmodyfikuj kod poniżej
    2. Wartości mają być podawane przy inicjalizacji
    3. Twórz instancje pierwszej klasy używając argumentów pozycyjnych
    4. Twórz instancje drugiej klasy używając argumentów nazwanych
    5. Uruchom doctesty - wszystkie muszą się powieść

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

    >>> assert isinstance(watney, Astronaut)
    >>> assert isinstance(nasa, SpaceAgency)
    >>> assert 'Watney' in vars(watney).values()
    >>> assert 'USA' in vars(watney).values()
    >>> assert '1969-07-21' in vars(watney).values()
    >>> assert 'NASA' in vars(nasa).values()
    >>> assert 'USA' in vars(nasa).values()
    >>> assert '1958-07-29' in vars(nasa).values()
"""


# Watney, USA, 1969-07-21
# NASA, USA, 1958-07-29

class Astronaut:
    pass


class SpaceAgency:
    pass


watney = Astronaut()
watney.name = 'Watney'
watney.country = 'USA'
watney.date = '1969-07-21'

nasa = SpaceAgency()
nasa.name = 'NASA'
nasa.country = 'USA'
nasa.date = '1958-07-29'