12.17. OOP Stringify Repr¶
Calling function
repr(obj)
callsobj.__repr__()
Method
obj.__repr__()
must returnstr
Dedicated for developers
Shows object representation
Copy-paste for creating object with the same values
Useful for debugging
Printing
list
will call__repr__()
method on each element
12.17.1. Inherited¶
Object without __repr__()
method overloaded prints their memory address:
>>> class Astronaut:
... def __init__(self, firstname, lastname):
... self.firstname = firstname
... self.lastname = lastname
>>>
>>>
>>> astro = Astronaut('Mark', 'Watney')
>>>
>>> astro
<__main__.Astronaut object at 0x...>
>>>
>>> repr(astro)
'<__main__.Astronaut object at 0x...>'
>>>
>>> astro.__repr__()
'<__main__.Astronaut object at 0x...>'
12.17.2. Overloaded¶
>>> class Astronaut:
... def __init__(self, firstname, lastname):
... self.firstname = firstname
... self.lastname = lastname
...
... def __repr__(self):
... clsname = self.__class__.__name__
... firstname = self.firstname
... lastname = self.lastname
... return f'{clsname}({firstname=}, {lastname=})'
>>>
>>>
>>> astro = Astronaut('Mark', 'Watney')
>>>
>>> astro
Astronaut(firstname='Mark', lastname='Watney')
>>>
>>> repr(astro)
"Astronaut(firstname='Mark', lastname='Watney')"
>>>
>>> astro.__repr__()
"Astronaut(firstname='Mark', lastname='Watney')"
12.17.3. Assignments¶
"""
* Assignment: OOP Stringify Repr
* Required: yes
* Complexity: easy
* Lines of code: 3 lines
* Time: 5 min
English:
1. Overload `repr()`
2. Run doctests - all must succeed
Polish:
1. Przeciąż `repr()`
2. Uruchom doctesty - wszystkie muszą się powieść
Tests:
>>> import sys; sys.tracebacklimit = 0
>>> from inspect import isclass, ismethod
>>> assert isclass(Iris)
>>> iris = Iris(DATA)
>>> assert hasattr(Iris, '__repr__')
>>> assert ismethod(iris.__repr__)
>>> repr(iris)
"Iris(features=[4.7, 3.2, 1.3, 0.2], label='setosa')"
"""
DATA = (4.7, 3.2, 1.3, 0.2, 'setosa')
# repr() -> Iris(features=[4.7, 3.2, 1.3, 0.2], label='setosa')
class Iris:
features: list
label: str
def __init__(self, data):
self.features = list(data[:-1])
self.label = str(data[-1])