__repr__ e __str__ in Python
Livello 4272 battiture
Questo mostra __repr__ e __str__ per diverse rappresentazioni di stringa. __repr__ è per sviluppatori, __str__ è per utenti finali.
Codice Python
# Definisce una classe Book con due rappresentazioni come stringa1class Book: # Il costruttore riceve un titolo e un autore2 def __init__(self, title, author): # Memorizza entrambi i valori come attributi di istanza3 self.title = title4 self.author = author5 # __repr__: forma precisa per gli sviluppatori, usata da repr()6 def __repr__(self): # Restituisce un testo simile alla chiamata del costruttore7 return f"Book('{self.title}', '{self.author}')"8 # __str__: forma leggibile per gli utenti, usata da str() e print()9 def __str__(self): # Restituisce "titolo by autore"10 return f"{self.title} by {self.author}"11 # Crea un'istanza di Book12b = Book("1984", "Orwell")# repr(b) chiama __repr__: Book('1984', 'Orwell')13print(repr(b))# str(b) chiama __str__: 1984 by Orwell14print(str(b))Output
Book('1984', 'Orwell')
1984 by OrwellEsercitati a digitare questo codice. I risultati non vengono registrati in classifica.
Simboli in questo codice
I simboli che digiti in questo codice Python e quante volte compaiono.
_× 12(× 9)× 9"× 8.× 6,× 4:× 4'× 4{× 4}× 4