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

16.5.1. Setattr, Getattr

  • Create attributes

  • Access existing attributes

  • Access not-existing attributes

>>> class User:
...     pass
>>>
>>> mark = User()

Create attributes:

>>> mark.firstname = 'Mark'
>>> mark.lastname = 'Watney'

Access existing attributes:

>>> print(mark.firstname)
Mark
>>>
>>> print(mark.lastname)
Watney
>>>
>>> print(f'Hello {mark.firstname} {mark.lastname}')
Hello Mark Watney

Access not-existing attributes:

>>> print(mark.age)
Traceback (most recent call last):
AttributeError: 'User' object has no attribute 'age'

16.5.2. State

  • vars() - returns a dict with current state of an object

  • Each instance has separate state

>>> class User:
...     pass
>>> mark = User()
>>> mark.firstname = 'Mark'
>>> mark.lastname = 'Watney'
>>> mark.age = 41
>>>
>>> vars(mark)
{'firstname': 'Mark', 'lastname': 'Watney', 'age': 41}
>>> melissa = User()
>>> melissa.firstname = 'Melissa'
>>> melissa.lastname = 'Lewis'
>>> melissa.age = 40
>>>
>>> vars(melissa)
{'firstname': 'Melissa', 'lastname': 'Lewis', 'age': 40}

16.5.3. Names, Values, Items

  • vars(obj).keys()

  • vars(obj).values()

  • vars(obj).items()

>>> class User:
...     pass
>>>
>>>
>>> mark = User()
>>> mark.firstname = 'Mark'
>>> mark.lastname = 'Watney'
>>> mark.age = 41
>>> list(vars(mark).keys())
['firstname', 'lastname', 'age']
>>> list(vars(mark).values())
['Mark', 'Watney', 41]
>>> list(vars(mark).items())  
[('firstname', 'Mark'),
 ('lastname', 'Watney'),
 ('age', 41)]

16.5.4. 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 Field Define
# - Difficulty: easy
# - Lines: 2
# - Minutes: 2

# %% English
# 1. Modify instance `mark`
# 2. Add field `firstname` with value 'Mark'
# 3. Add field `lastname` with value 'Watney'
# 4. Run doctests - all must succeed

# %% Polish
# 1. Zmodyfikuj instancję `mark`
# 2. Dodaj pole `firstname` o wartości 'Mark'
# 3. Dodaj pole `lastname` o wartości 'Watney'
# 4. Uruchom doctesty - wszystkie muszą się powieść

# %% Tests
"""
>>> 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(mark, User)
>>> assert hasattr(mark, 'firstname')
>>> assert hasattr(mark, 'lastname')
>>> assert getattr(mark, 'firstname') == 'Mark'
>>> assert getattr(mark, 'lastname') == 'Watney'
"""

class User:
    pass

mark = User()

# Modify instance `mark`
# Add field `firstname` with value 'Mark'
# type: str
...

# Modify instance `mark`
# Add field `lastname` with value 'Watney'
# type: str
...


# %% 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 Field Define
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2

# %% English
# 1. Modify instance `mark`
# 2. Add field `_authenticated` with value False
# 3. Run doctests - all must succeed

# %% Polish
# 1. Zmodyfikuj instancję `mark`
# 2. Dodaj pole `_authenticated` o wartości False
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Tests
"""
>>> 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(mark, User)
>>> assert hasattr(mark, '_authenticated')
>>> assert getattr(mark, '_authenticated') is False
"""

class User:
    pass

mark = User()

# Modify instance `mark`
# Add field `_authenticated` with value False
# type: bool
...


# %% 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 Field Vars
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2

# %% English
# 1. Use instance `mark`
# 2. Define `result: dict` with current state of `mark` object
#    (all attributes and values in dict format)
# 3. Run doctests - all must succeed

# %% Polish
# 1. Użyj instancji `mark`
# 2. Zdefiniuj `result: dict` z aktualnym stanem obiektu `mark`
#    (wszystkie atrybuty i wartości w formacie dict)
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Tests
"""
>>> 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(mark, User)
>>> assert hasattr(mark, 'firstname')
>>> assert hasattr(mark, 'lastname')
>>> assert hasattr(mark, '_authenticated')
>>> assert getattr(mark, 'firstname') == 'Mark'
>>> assert getattr(mark, 'lastname') == 'Watney'
>>> assert getattr(mark, '_authenticated') is False
"""

class User:
    pass

mark = User()
mark.firstname = 'Mark'
mark.lastname = 'Watney'
mark._authenticated = False


# Define `result: dict` with current state of `mark` object
# (all attributes and values in dict format)
# type: dict[str, str|bool]
result = ...