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.firstname = 'Alice'
>>> alice.lastname = 'Apricot'

17.5.3. Getattr

  • Access existing attributes

  • Access not-existing attributes

Access existing attributes:

>>> print(alice.firstname)
Alice
>>>
>>> print(alice.lastname)
Apricot
>>>
>>> print(f'Hello {alice.firstname} {alice.lastname}')
Hello Alice Apricot

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 object

  • Each instance has separate state

>>> vars(alice)
{'firstname': 'Alice', 'lastname': 'Apricot'}

17.5.5. Names, Values, Items

  • vars(obj).keys()

  • vars(obj).values()

  • vars(obj).items()

>>> list(vars(alice).keys())
['firstname', 'lastname']
>>> list(vars(alice).values())
['Alice', 'Apricot']
>>> list(vars(alice).items())
[('firstname', 'Alice'),
 ('lastname', 'Apricot')]
>>> for field, value in vars(alice).items():
...     print(f'{field=}, {value=}')
...
field='firstname', value='Alice'
field='lastname', value='Apricot'

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 -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 -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. Use instance `alice`
# 2. Define `result: dict` with current state of `alice` object
#    (all attributes and values in dict format)
# 3. Run doctests - all must succeed

# %% Polish
# 1. Użyj instancji `alice`
# 2. Zdefiniuj `result: dict` z aktualnym stanem obiektu `alice`
#    (wszystkie atrybuty i wartości w formacie dict)
# 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
"""

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -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 = ...