16.16. OOP Stringify Str

  • Dedicated for end-user of your class

  • Calling function print(obj) calls str(obj)

  • Calling function str(obj) calls obj.__str__()

  • Calling f'{obj}' calls obj.__str__()

  • Calling f'{obj!s}' calls obj.__str__()

  • Method obj.__str__() must return str

16.16.1. Without Method

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>'

16.16.2. Overloaded

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.16.3. Assignments

"""
* Assignment: OOP Stringify Str
* Type: class assignment
* Complexity: easy
* Lines of code: 3 lines
* Time: 5 min

English:
    1. Use class `User`
    2. Define `__str__` method for printing instance information
    3. Method should display attributes and their values
       example: `Mark Watney`
    3. Run doctests - all must succeed

Polish:
    1. Użyj klasy `User`
    2. Zdefiniuj metodę `__str__` do informaji o instancji
    3. Method should display attributes and their values
       example: `Mark Watney`
    3. Uruchom doctesty - wszystkie muszą się powieść

Tests:
    >>> import sys; sys.tracebacklimit = 0
    >>> 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'
"""

# Define `__str__` method for printing instance information
# Method should display attributes and their values
# example: `Mark Watney`
class User:
    def __init__(self, firstname, lastname):
        self.firstname = firstname
        self.lastname = lastname