7.2.4 String Representation with __str__ and __repr__

Unit: Unit 7: Introduction to Classes • Interactive Practice

Quick Answer & Summary:

Interactive Python programming tutorial and practice in your browser.

Interactive Challenge (Run Live in Browser):

# Provide human-readable and developer-friendly string representations
class Employee:
    def __init__(self, name, role, salary):
        self.name = name
        self.role = role
        self.salary = salary

    # User-friendly representation for print() and str()
    def __str__(self):
        return f"{self.name} ({self.role}) - ${self.salary:,}/yr"

    # Technical, unambiguous representation for debugging and interactive consoles
    def __repr__(self):
        return f"Employee('{self.name}', '{self.role}', {self.salary})"

dev = Employee("Maya Lin", "Lead Architect", 145000)

print("str output:", str(dev))
print("repr output:", repr(dev))
Open in Live Interactive Python Sandbox →