17.5. OOP Field
Attributes are also known as "Properties" or "Fields"
Attributes store information for instances
Access field values using dot (
.
) notation
- field
Variable inside the class. Can be used as a synonym of property or attribute.
- property
Variable inside the class. Can be used as a synonym of field or attribute.
- state
Current values of all variables in a class. Changes during lifetime of an object. Represents current state of an object. State could be retrieved by using
vars(obj)
- attribute
Variable inside the class. Can be used as a synonym of field or property. In Python, methods also can be described as attributes, but justification for that is a bit more complex which will be introduced later in a book.
- namespace
Container for storing related data
17.5.1. SetUp
>>> class User:
... pass
>>>
>>>
>>> alice = User()
17.5.2. Setattr
Create attributes
Create attributes:
>>> alice.username = 'alice'
>>> alice.password = 'secret'
17.5.3. Getattr
Access existing attributes
Access not-existing attributes
Access existing attributes:
>>> print(alice.username)
alice
>>>
>>> print(alice.password)
secret
>>>
>>> print(f'Hello {alice.username}')
Hello alice
Access not-existing attributes:
>>> print(alice.email)
Traceback (most recent call last):
AttributeError: 'User' object has no attribute 'email'
17.5.4. State
vars()
- returns a dict with current state of an objectEach instance has separate state
>>> vars(alice)
{'username': 'alice', 'password': 'secret'}
17.5.5. Names, Values, Items
vars(obj).keys()
vars(obj).values()
vars(obj).items()
>>> list(vars(alice).keys())
['username', 'password']
>>> list(vars(alice).values())
['alice', 'secret']
>>> list(vars(alice).items())
[('username', 'alice'),
('password', 'secret')]
>>> for field, value in vars(alice).items():
... print(f'{field=}, {value=}')
...
field='username', value='alice'
field='password', value='secret'
17.5.6. Assignments
# %% About
# - Name: OOP Field Define
# - Difficulty: easy
# - Lines: 2
# - Minutes: 2
# %% 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
# %% English
# 1. Modify instance `alice`
# 2. Add field `firstname` with value 'Alice'
# 3. Add field `lastname` with value 'Apricot'
# 4. Run doctests - all must succeed
# %% Polish
# 1. Zmodyfikuj instancję `alice`
# 2. Dodaj pole `firstname` o wartości 'Alice'
# 3. Dodaj pole `lastname` o wartości 'Apricot'
# 4. Uruchom doctesty - wszystkie muszą się powieść
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> from pprint import pprint
>>> from inspect import isclass
>>> assert isclass(User)
>>> assert isinstance(alice, User)
>>> assert hasattr(alice, 'firstname')
>>> assert hasattr(alice, 'lastname')
>>> assert getattr(alice, 'firstname') == 'Alice'
>>> assert getattr(alice, 'lastname') == 'Apricot'
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`
# %% Imports
# %% Types
User: type
firstname: str
lastname: str
# %% Data
class User:
pass
alice = User()
# %% Result
# %% About
# - Name: OOP Field Define
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2
# %% 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
# %% English
# 1. Modify instance `alice`
# 2. Add field `authenticated` with value False
# 3. Run doctests - all must succeed
# %% Polish
# 1. Zmodyfikuj instancję `alice`
# 2. Dodaj pole `authenticated` o wartości False
# 3. Uruchom doctesty - wszystkie muszą się powieść
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> from pprint import pprint
>>> from inspect import isclass
>>> assert isclass(User)
>>> assert isinstance(alice, User)
>>> assert hasattr(alice, 'authenticated')
>>> assert getattr(alice, 'authenticated') is False
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`
# %% Imports
# %% Types
User: type
authenticated: bool
# %% Data
class User:
pass
alice = User()
# %% Result
# %% About
# - Name: OOP Field Vars
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2
# %% 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
# %% English
# 1. Get state of `alice` object (all attributes and values in dict format)
# 2. Define `result: dict` with the result
# 3. Run doctests - all must succeed
# %% Polish
# 1. Pobierz stan obiektu `alice` (wszystkie atrybuty i wartości w formacie dict)
# 2. Zdefiniuj `result: dict` z wynikiem
# 3. Uruchom doctesty - wszystkie muszą się powieść
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> from pprint import pprint
>>> from inspect import isclass
>>> assert isclass(User)
>>> assert isinstance(alice, User)
>>> assert hasattr(alice, 'firstname')
>>> assert hasattr(alice, 'lastname')
>>> assert hasattr(alice, 'authenticated')
>>> assert getattr(alice, 'firstname') == 'Alice'
>>> assert getattr(alice, 'lastname') == 'Apricot'
>>> assert getattr(alice, 'authenticated') is False
>>> assert type(result) is dict
>>> assert len(result) == 3
>>> assert 'firstname' in result
>>> assert 'lastname' in result
>>> assert 'authenticated' in result
>>> result
{'firstname': 'Alice', 'lastname': 'Apricot', 'authenticated': False}
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`
# %% Imports
# %% Types
result: dict[str, str|bool]
# %% Data
class User:
pass
alice = User()
alice.firstname = 'Alice'
alice.lastname = 'Apricot'
alice.authenticated = False
# %% Result
result = ...