16.6. OOP Init
__init__()
- initializer methodIt's a first method run after object is initiated
All classes has default
__init__()
- constructor
Method called when Python creates an instance of a class. Constructor is responsible for creating an object. Constructor returns an instance.
- initializer
Method called when Python creates an instance of a class. Initializer is responsible for initializing empty object with values. Initializer should return
None
.
16.6.1. Without Arguments
Initializer method without arguments:
>>> class User:
... def __init__(self):
... print('hello')
>>>
>>>
>>> mark = User()
hello
>>>
>>> melissa = User()
hello
16.6.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.6.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.6.4. Constant Attributes
>>> class User:
... def __init__(self):
... self._authenticated = False
>>> mark = User()
>>> melissa = User()
>>> vars(mark)
{'_authenticated': False}
>>>
>>> vars(melissa)
{'_authenticated': False}
16.6.5. Variable Attributes
>>> class User:
... def __init__(self, a, b):
... self.firstname = a
... self.lastname = b
>>> mark = User('Mark', 'Watney')
>>> melissa = User(a='Melissa', b='Lewis')
>>> vars(mark)
{'firstname': 'Mark', 'lastname': 'Watney'}
>>> vars(melissa)
{'firstname': 'Melissa', 'lastname': 'Lewis'}
16.6.6. Better Names
>>> class User:
... def __init__(self, firstname, lastname):
... self.firstname = firstname
... self.lastname = lastname
>>> mark = User('Mark', 'Watney')
>>> vars(mark)
{'firstname': 'Mark', 'lastname': 'Watney'}
>>> mark = User(firstname='Mark', lastname='Watney')
>>> vars(mark)
{'firstname': 'Mark', 'lastname': 'Watney'}
16.6.7. Combine Attributes
You can combine
firstname
andlastname
intoself.name
>>> class User:
... def __init__(self, firstname, lastname):
... self.name = f'{firstname} {lastname}'
>>>
>>>
>>> mark = User('Mark', 'Watney')
>>> vars(mark)
{'name': 'Mark Watney'}
>>> print(mark.name)
Mark Watney
>>>
>>> print(mark.firstname)
Traceback (most recent call last):
AttributeError: 'User' object has no attribute 'firstname'
>>>
>>> print(mark.lastname)
Traceback (most recent call last):
AttributeError: 'User' object has no attribute 'lastname'
16.6.8. Validation
>>> class User:
... def __init__(self, firstname, lastname, age):
... if not 0 <= age <= 130:
... raise ValueError('Age must be between 0 and 130')
... self.firstname = firstname
... self.lastname = lastname
... self.age = age
>>> mark = User('Mark', 'Watney', age=42)
>>> mark = User('Mark', 'Watney', age=-1)
Traceback (most recent call last):
ValueError: Age must be between 0 and 130
16.6.9. Use Case - 1
>>> class Point:
... def __init__(self, x, y):
... self.x = x
... self.y = y
>>>
>>>
>>> a = Point(10, 20)
>>> b = Point(10, y=20)
>>> c = Point(x=10, y=20)
>>> d = Point(y=20, x=10)
16.6.10. Use Case - 2
>>> class Point:
... def __init__(self, x, y, z=0):
... self.x = x
... self.y = y
... self.z = z
>>> a = Point(10, 20)
>>> b = Point(10, y=20)
>>> c = Point(x=10, y=20)
>>> d = Point(y=20, x=10)
>>> e = Point(10, 20, 30)
>>> f = Point(10, 20, z=30)
>>> g = Point(10, y=20, z=30)
>>> h = Point(10, z=30, y=20)
>>> i = Point(x=10, y=20, z=30)
>>> j = Point(x=10, z=30, y=20)
>>> k = Point(y=20, x=10, z=30)
>>> l = Point(y=20, z=30, x=10)
>>> m = Point(z=30, x=10, y=20)
>>> n = Point(z=30, y=20, x=10)
16.6.11. Use Case - 3
>>> class Iris:
... 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
>>> setosa = Iris(5.1, 3.5, 1.4, 0.2, 'setosa')
>>> virginica = Iris(
... sepal_length=5.8,
... sepal_width=2.7,
... petal_length=5.1,
... petal_width=1.9,
... species='virginica')
16.6.12. Use Case - 4
>>> from random import randint, seed
>>> seed(0)
>>>
>>>
>>> class Hero:
... def __init__(self, name, position_x, position_y):
... self.name = name
... self.position = (position_x, position_y)
... self.health = randint(50,100)
>>>
>>>
>>> mark = Hero('Mark', position_x=10, position_y=20)
>>> vars(mark)
{'name': 'Mark', 'position': (10, 20), 'health': 74}
16.6.13. Use Case - 5
>>> from random import randint, seed
>>> seed(0)
>>>
>>>
>>> class Hero:
... def __init__(self, name, health_min=10, health_max=100):
... self.name = name
... self.position = (0, 0)
... self.health = randint(health_min,health_max)
>>>
>>>
>>> mark = Hero('Mark', health_min=50)
>>> vars(mark)
{'name': 'Mark', 'position': (0, 0), 'health': 74}
16.6.14. Assignments
# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% About
# - Name: OOP Init Hello
# - Difficulty: easy
# - Lines: 2
# - Minutes: 2
# %% English
# 1. Modify `User` class:
# - Define initialization method
# - Method should print 'hello' at object creation
# 2. Non-functional requirements:
# - Do not store any values in the class
# - Run doctests - all must succeed
# %% Polish
# 1. Zmodyfikuj klasę `User`:
# - Zdefiniuj metodę inicjalizacyjną
# - Metoda powinna wypisać 'hello' przy tworzeniu obiektu
# 2. Wymagania niefunkcjonalne:
# - Nie przechowuj żadnych wartości w klasie
# - Uruchom doctesty - wszystkie muszą się powieść
# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> from inspect import isclass
>>> assert isclass(User)
>>> assert hasattr(User, '__init__')
>>> result = User()
hello
>>> vars(result)
{}
"""
# Define initialization method
# Method should print 'hello' at object creation
class User:
...
# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% About
# - Name: OOP Init Fields
# - Difficulty: easy
# - Lines: 3
# - Minutes: 2
# %% English
# 1. Modify `User` class:
# - Define initialization method
# - Method should set `_authenticated` attribute to `False`
# 2. Non-functional requirements:
# - Run doctests - all must succeed
# %% Polish
# 1. Zmodyfikuj klasę `User`:
# - Zdefiniuj metodę inicjalizacyjną
# - Metoda powinna ustawić atrybut `_authenticated` na `False`
# 2. Wymagania niefunkcjonalne:
# - Uruchom doctesty - wszystkie muszą się powieść
# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> from inspect import isclass
>>> assert isclass(User)
>>> assert hasattr(User, '__init__')
>>> result = User()
>>> vars(result)
{'_authenticated': False}
"""
# Define initialization method
# Method should set `_authenticated` attribute to `False`
class User:
...
# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% About
# - Name: OOP Init Parameters
# - Difficulty: easy
# - Lines: 3
# - Minutes: 2
# %% English
# 1. Modify `User` class:
# - Define initialization method with parameters `firstname` and `lastname`
# - Method should set `firstname` attribute to the value of `firstname` parameter
# - Method should set `lastname` attribute to the value of `lastname` parameter
# 2. Non-functional requirements:
# - Run doctests - all must succeed
# %% Polish
# 1. Zmodyfikuj klasę `User`:
# - Zdefiniuj metodę inicjalizacyjną z parametrami `firstname` i `lastname`
# - Metoda powinna ustawić atrybut `firstname` na wartość parametru `firstname`
# - Metoda powinna ustawić atrybut `lastname` na wartość parametru `lastname`
# 2. Wymagania niefunkcjonalne:
# - Uruchom doctesty - wszystkie muszą się powieść
# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> from inspect import isclass
>>> assert isclass(User)
>>> assert hasattr(User, '__init__')
>>> mark = User('Mark', 'Watney')
>>> vars(mark)
{'firstname': 'Mark', 'lastname': 'Watney'}
>>> mark = User(firstname='Melissa', lastname='Lewis')
>>> vars(mark)
{'firstname': 'Melissa', 'lastname': 'Lewis'}
"""
# Define initialization method with parameters `firstname` and `lastname`
# Method should set `firstname` attribute to the value of `firstname` parameter
# Method should set `lastname` attribute to the value of `lastname` parameter
class User:
...