__repr__ e __str__ em Python
Nível 4272 toques
Isso mostra __repr__ e __str__ para diferentes representações de string. __repr__ é para desenvolvedores, __str__ é para usuários finais.
Código Python
# Define uma classe Book com duas representações em string1class Book: # O construtor recebe um título e um autor2 def __init__(self, title, author): # Guarda os dois valores como atributos de instância3 self.title = title4 self.author = author5 # __repr__: forma precisa para desenvolvedores, usada por repr()6 def __repr__(self): # Retorna um texto parecido com a chamada do construtor7 return f"Book('{self.title}', '{self.author}')"8 # __str__: forma legível para usuários, usada por str() e print()9 def __str__(self): # Retorna "título by autor"10 return f"{self.title} by {self.author}"11 # Cria uma instância de Book12b = Book("1984", "Orwell")# repr(b) chama __repr__: Book('1984', 'Orwell')13print(repr(b))# str(b) chama __str__: 1984 by Orwell14print(str(b))Saída
Book('1984', 'Orwell')
1984 by OrwellPratique digitando este código. Os resultados não são registrados no ranking.
Símbolos deste código
Os símbolos que você digita neste código Python e quantas vezes aparecem.
_× 12(× 9)× 9"× 8.× 6,× 4:× 4'× 4{× 4}× 4