CKTIS / Python
object.__repr__
Il metodo di rappresentazione restituisce una stringa per identificare chiaramente un oggetto durante il debug.
Versione: Python 3.14; repository image, production runtime not attested
Sintassi
representation = repr(obj)Il metodo di rappresentazione restituisce una stringa per identificare chiaramente un oggetto durante il debug.
object.__repr__
Lo usano repr e !r e la rappresentazione degli elementi di una lista. Un’espressione ricostruibile è auspicabile se possibile ma non garantita. Il risultato deve essere str.
!r rende visibile il fine riga come barra inversa seguita da n.
class Wrong:
def __repr__(self): return 8
try: repr(Wrong())
except TypeError: pass
else: raise AssertionError
class Fallback:
def __repr__(self): return 'record'
assert str(Fallback())=='record'
Esempi
class Token:
def __init__(self, text): self.text=text
def __repr__(self): return f"Token({self.text!r})"
t=Token("a\nb")
print(repr(t))
print([t])
Risultato
Token('a\nb')
[Token('a\nb')]!r rende visibile il fine riga come barra inversa seguita da n.