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.
In this exercise, you will continue working with the Employee
class from Chapter 2.
This exercise is part of the course
Object-Oriented Programming in Python
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
class Employee:
def __init__(self, name, salary=30000):
self.name, self.salary = name, salary
# Add the __str__() method
____
emp1 = Employee("Amar Howard", 30000)
print(emp1)
emp2 = Employee("Carolyn Ramirez", 35000)
print(emp2)