__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 stringa
1class Book:
# Il costruttore riceve un titolo e un autore
2 def __init__(self, title, author):
# Memorizza entrambi i valori come attributi di istanza
3 self.title = title
4 self.author = author
5
# __repr__: forma precisa per gli sviluppatori, usata da repr()
6 def __repr__(self):
# Restituisce un testo simile alla chiamata del costruttore
7 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 Book
12b = Book("1984", "Orwell")
# repr(b) chiama __repr__: Book('1984', 'Orwell')
13print(repr(b))
# str(b) chiama __str__: 1984 by Orwell
14print(str(b))

Output

Book('1984', 'Orwell')
1984 by Orwell
Esercitati a digitare questo codice

Esercitati 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

Altri esempi Python di livello 4

← Pratica di digitazione Python