Search⌘ K
AI Features

Solution Review: Printing and Comparing the Class Objects

Explore how to add string representation and comparison methods in Python classes. Understand using __str__ for readable printing and defining __eq__, __lt__, and __ge__ to compare class objects efficiently.

We'll cover the following...

Solution

Python 3.5
class Person(object):
def __init__(self, name, age, purchases):
self.name = name
self.age = age
self.purchases = purchases
def __str__(self):
return self.name + " is " + str(self.age) + " years old"
def __eq__(self, person):
return self.purchases == person.purchases
def __lt__(self, person):
return self.purchases < person.purchases
def __ge__(self, person):
return self.purchases >= person.purchases
# name = Josh, age = 25
p = Person("Josh", 25, 6)
p2 = Person("Jill", 22, 10)
p3 = Person("Jim", 30, 9)
print(str(p))
print('p == p2 result:', p == p2)
print('p < p3 result:', p < p3)
print('p2 >= p3 result:', p2 >= p3)

Explanation

First, we need to add our __str__ method inside the Person class at line 7. ...