Operatorüberladung: String-Darstellung

Objektorientierte Programmierung in Python

Alex Yarosh

Content Quality Analyst @ DataCamp

Objekt drucken

class Customer:
  def __init__(self, name, balance):
    self.name, self.balance = name, balance 

cust = Customer("Maryam Azar", 3000)
print(cust)
<__main__.Customer at 0x1f8598e2240>

 

import numpy as np

arr = np.array([1,2,3])
print(arr)
[1 2 3]
Objektorientierte Programmierung in Python

__str__()

  • print(obj), str(obj)
print(np.array([1,2,3]))
[1 2 3]
str(np.array([1,2,3]))
[1 2 3]
  • informell, für Endnutzer
  • string-Darstellung

__repr__()

  • repr(obj), Konsolenausgabe
repr(np.array([1,2,3]))
array([1,2,3])
np.array([1,2,3])
array([1,2,3])
  • formell, für Entwickler
  • reproduzierbare repräsentation
  • Fallback für print()
Objektorientierte Programmierung in Python

Implementierung: str

class Customer:
  def __init__(self, name, balance):
    self.name, self.balance = name, balance 

  def __str__(self):
    cust_str = """
    Kunde:
      Name: {name}
      Guthaben: {balance}
    """.format(name = self.name, \
               balance = self.balance)
    return cust_str

cust = Customer("Maryam Azar", 3000)

# Ruft implizit __str__() auf
print(cust)
Kunde:
  Name: Maryam Azar
  Guthaben: 3000

Objektorientierte Programmierung in Python

Implementierung: repr

class Customer:
  def __init__(self, name, balance):
    self.name, self.balance = name, balance 

  def __repr__(self):
    # Beachte die '...' um den Namen 
    return "Customer('{name}', {balance})".format(name = self.name, balance = self.balance)

cust = Customer("Maryam Azar", 3000) cust # <--- # Ruft implizit __repr__() auf
Customer('Maryam Azar', 3000) # <--- nicht Customer(Maryam Azar, 3000)
  • String-Argumente in der __repr__()-Ausgabe in Anführungszeichen setzen
Objektorientierte Programmierung in Python

Lass uns üben!

Objektorientierte Programmierung in Python

Preparing Video For Download...