16.8. OOP Stringification
str()
- Dedicated for end-users (object stringification)repr()
- Dedicated for developers (object representation)
16.8.1. Str
Dedicated for end-users (object stringification)
Calling function
print(obj)
callsstr(obj)
Calling function
str(obj)
callsobj.__str__()
Calling
f'{obj}'
callsobj.__str__()
Calling
f'{obj!s}'
callsobj.__str__()
Method
obj.__str__()
must returnstr
Object without __str__()
method overloaded prints their memory address:
>>> class User:
... def __init__(self, firstname, lastname):
... self.firstname = firstname
... self.lastname = lastname
>>>
>>>
>>> mark = User('Mark', 'Watney')
>>>
>>> print(mark)
<__main__.User object at 0x10aef7450>
>>>
>>> str(mark)
'<__main__.User object at 0x10aef7450>'
>>>
>>> mark.__str__()
'<__main__.User object at 0x10aef7450>'
>>>
>>> f'{mark}'
'<__main__.User object at 0x10aef7450>'
>>>
>>> f'{mark!s}'
'<__main__.User object at 0x10aef7450>'
Objects can verbose print if __str__()
method is present:
>>> class User:
... def __init__(self, firstname, lastname):
... self.firstname = firstname
... self.lastname = lastname
...
... def __str__(self):
... return f'{self.firstname} {self.lastname}'
...
>>> mark = User('Mark', 'Watney')
>>>
>>> print(mark)
Mark Watney
>>>
>>> str(mark)
'Mark Watney'
>>>
>>> mark.__str__()
'Mark Watney'
>>>
>>> f'{mark}'
'Mark Watney'
>>>
>>> f'{mark!s}'
'Mark Watney'
16.8.2. Repr
Dedicated for developers (object representation)
Calling function
repr(obj)
callsobj.__repr__()
Method
obj.__repr__()
must returnstr
Copy-paste for creating object with the same values
Useful for debugging
Printing
list
will call__repr__()
method on each element
Object without __repr__()
method overloaded prints their memory address:
>>> class User:
... def __init__(self, firstname, lastname):
... self.firstname = firstname
... self.lastname = lastname
...
...
>>> mark = User('Mark', 'Watney')
>>>
>>> mark
<__main__.User object at 0x10aef7450>
>>>
>>> repr(mark)
'<__main__.User object at 0x10aef7450>'
>>>
>>> mark.__repr__()
'<__main__.User object at 0x10aef7450>'
>>>
>>> f'{mark!r}'
'<__main__.User object at 0x10aef7450>'
Objects can verbose print if __repr__()
method is present:
>>> class User:
... def __init__(self, firstname, lastname):
... self.firstname = firstname
... self.lastname = lastname
...
... def __repr__(self):
... firstname = self.firstname
... lastname = self.lastname
... return f'User({firstname=}, {lastname=})'
...
...
>>> mark = User('Mark', 'Watney')
>>>
>>> mark
User(firstname='Mark', lastname='Watney')
>>>
>>> repr(mark)
"User(firstname='Mark', lastname='Watney')"
>>>
>>> mark.__repr__()
"User(firstname='Mark', lastname='Watney')"
>>>
>>> f'{mark!r}'
"User(firstname='Mark', lastname='Watney')"
16.8.3. Case Study
>>> import datetime
>>>
>>> today = datetime.date(2000, 1, 2)
>>> str(today)
'2000-01-02'
>>> repr(today)
'datetime.date(2000, 1, 2)'
16.8.4. Use Case - 1
>>> from pprint import pprint
Problem:
>>> class User:
... def __init__(self, firstname, lastname):
... self.firstname = firstname
... self.lastname = lastname
>>>
>>>
>>> mark = User('Mark', 'Watney')
>>> melissa = User('Melissa', 'Lewis')
>>> rick = User('Rick', 'Martinez')
>>>
>>> result = []
>>> result.append(mark)
>>> result.append(melissa)
>>> result.append(rick)
>>>
>>> result
[<__main__.User at 0x10c37bf80>,
<__main__.User at 0x10c3789e0>,
<__main__.User at 0x10c37a990>]
Solution:
>>> class User:
... def __init__(self, firstname, lastname):
... self.firstname = firstname
... self.lastname = lastname
...
... def __str__(self):
... return f'{self.firstname} {self.lastname}'
...
... def __repr__(self):
... cls = self.__class__.__name__
... firstname = self.firstname
... lastname = self.lastname
... return f'{cls}({firstname=}, {lastname=})'
>>>
>>>
>>> mark = User('Mark', 'Watney')
>>> melissa = User('Melissa', 'Lewis')
>>> rick = User('Rick', 'Martinez')
>>>
>>> result = []
>>> result.append(mark)
>>> result.append(melissa)
>>> result.append(rick)
>>>
>>> pprint(result)
[User(firstname='Mark', lastname='Watney'),
User(firstname='Melissa', lastname='Lewis'),
User(firstname='Rick', lastname='Martinez')]
16.8.5. 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 Stringification Str
# - Difficulty: easy
# - Lines: 3
# - Minutes: 3
# %% English
# 1. Modify class `User`
# 2. Define new method `__str__` which returns users firstname and lastname
# example: `Mark Watney`
# 3. Run doctests - all must succeed
# %% Polish
# 1. Zmodyfikuj klasę `User`
# 2. Zdefiniuj nową metodę `__str__`, która zwraca imię i nazwisko użytkownika
# przykład: `Mark Watney`
# 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 hasattr(User, '__init__')
>>> assert hasattr(User, '__str__')
>>> mark = User('Mark', 'Watney')
>>> result = str(mark)
>>> pprint(result)
'Mark Watney'
"""
# Modify class `User`
# Define new method `__str__` which returns users firstname and lastname
# Example: `Mark Watney`
class User:
def __init__(self, firstname, lastname):
self.firstname = firstname
self.lastname = lastname
# %% 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 Stringification Repr
# - Difficulty: easy
# - Lines: 3
# - Minutes: 3
# %% English
# 1. Modify class `User`
# 2. Define new method `__repr__` for displaying class name, fields and their values
# example: `User(firstname='Mark', lastname='Watney')`
# 3. Run doctests - all must succeed
# %% Polish
# 1. Zmodyfikuj klasę `User`
# 2. Zdefiniuj nową metodę `__repr__` do wyświetlania nazwy klasy, pól i ich wartości
# przykład: `User(firstname='Mark', lastname='Watney')`
# 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 hasattr(User, '__init__')
>>> assert hasattr(User, '__repr__')
>>> mark = User('Mark', 'Watney')
>>> result = repr(mark)
>>> pprint(result)
"User(firstname='Mark', lastname='Watney')"
"""
# Modify class `User`
# Define new method `__repr__` for displaying class name, fields and their values
# Example: `User(firstname='Mark', lastname='Watney')`
class User:
def __init__(self, firstname, lastname):
self.firstname = firstname
self.lastname = lastname