String representation of objects

Implementation of 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

Implementation of 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__()

Surround string arguments with quotation marks in the __repr__() output.

String representation of objects

There are two special methods in Python that return a string representation of an object. __str__() is called when you use print() or str() on an object, and __repr__() is called when you use repr() on an object, print the object in the console without calling print(), or instead of __str__() if __str__() is not defined.

__str__() is supposed to provide a “user-friendly” output describing an object, and __repr__() should return the expression that, when evaluated, will return the same object, ensuring the reproducibility of your code.

You should always define at least one of the string representation methods for your object to make sure that the person using your class can get important information about the object easily.

Example exercise with __str__() :

class Employee:
    def __init__(self, name, salary=30000):
        self.name, self.salary = name, salary
            
    # Add the __str__() method
    def __str__(self):
        cust_str = """
        Employee name: {name}
        Employee salary: {salary}
        """.format(name = self.name, \
                    salary = self.salary)
        return cust_str

emp1 = Employee("Amar Howard", 30000)
print(emp1)
emp2 = Employee("Carolyn Ramirez", 35000)
print(emp2)

Example exercise with __repr__() :

class Employee:
    def __init__(self, name, salary=30000):
        self.name, self.salary = name, salary
      

    def __str__(self):
        s = "Employee name: {name}\nEmployee salary: {salary}".format(name=self.name, salary=self.salary)      
        return s
      
    # Add the __repr__method  
    def __repr__(self):
        return "Employee('{name}', {salary})".format(name = self.name, salary = self.salary)

emp1 = Employee("Amar Howard", 30000)
print(repr(emp1))
emp2 = Employee("Carolyn Ramirez", 35000)
print(repr(emp2))

Add a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.