Operator overloading: string representation

Object-Oriented Programming in Python

Alex Yarosh

Content Quality Analyst @ DataCamp

Printing an object

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]
Object-Oriented Programming 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]
  • informal, for end user
  • string representation

__repr__()

  • repr(obj), printing in console
repr(np.array([1,2,3]))
array([1,2,3])
np.array([1,2,3])
array([1,2,3])
  • formal, for developer
  • reproducible representation
  • fallback for print()
Object-Oriented Programming in Python

Implementation: str

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

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

cust = Customer("Maryam Azar", 3000)

# Will implicitly call __str__()
print(cust)
Customer:
  name: Maryam Azar
  balance: 3000

Object-Oriented Programming in Python

Implementation: repr

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

  def __repr__(self):
    # Notice the '...' around name 
    return "Customer('{name}', {balance})".format(name = self.name, balance = self.balance)

cust = Customer("Maryam Azar", 3000) cust # <--- # Will implicitly call __repr__()
Customer('Maryam Azar', 3000) # <--- not Customer(Maryam Azar, 3000)
  • Surround string arguments with quotation marks in the __repr__() output
Object-Oriented Programming in Python

Let's practice!

Object-Oriented Programming in Python

Preparing Video For Download...