__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 string
1class Book:
# O construtor recebe um título e um autor
2 def __init__(self, title, author):
# Guarda os dois valores como atributos de instância
3 self.title = title
4 self.author = author
5
# __repr__: forma precisa para desenvolvedores, usada por repr()
6 def __repr__(self):
# Retorna um texto parecido com a chamada do construtor
7 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 Book
12b = Book("1984", "Orwell")
# repr(b) chama __repr__: Book('1984', 'Orwell')
13print(repr(b))
# str(b) chama __str__: 1984 by Orwell
14print(str(b))

Saída

Book('1984', 'Orwell')
1984 by Orwell
Praticar digitando este código

Pratique 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

Mais exemplos de Python de nível 4

← Prática de digitação de Python