__repr__ und __str__ in Python

Level 4272 Tastenanschläge

Dies zeigt __repr__ und __str__ für verschiedene String-Darstellungen. __repr__ ist für Entwickler, __str__ ist für Endbenutzer.

Python-Code

# Definiere eine Book-Klasse mit zwei String-Darstellungen
1class Book:
# Der Konstruktor erhält Titel und Autor
2 def __init__(self, title, author):
# Speichere beide Werte als Instanzattribute
3 self.title = title
4 self.author = author
5
# __repr__: eindeutige Form für Entwickler, von repr() verwendet
6 def __repr__(self):
# Gib einen Text zurück, der wie der Konstruktoraufruf aussieht
7 return f"Book('{self.title}', '{self.author}')"
8
# __str__: lesbare Form für Benutzer, von str() und print() verwendet
9 def __str__(self):
# Gib "Titel by Autor" zurück
10 return f"{self.title} by {self.author}"
11
# Erstelle eine Book-Instanz
12b = Book("1984", "Orwell")
# repr(b) ruft __repr__ auf: Book('1984', 'Orwell')
13print(repr(b))
# str(b) ruft __str__ auf: 1984 by Orwell
14print(str(b))

Ausgabe

Book('1984', 'Orwell')
1984 by Orwell
Diesen Code tippen üben

Übe, diesen Code zu tippen. Ergebnisse werden nicht in der Rangliste gespeichert.

Symbole in diesem Code

Die Symbole, die du in diesem Python-Code tippst, und wie oft sie vorkommen.

  • _× 12
  • (× 9
  • )× 9
  • "× 8
  • .× 6
  • ,× 4
  • :× 4
  • '× 4
  • {× 4
  • }× 4

Weitere Python-Beispiele auf Level 4

← Python-Tippübungen