...

/

Solution Review: Printing and Comparing the Class Objects

Solution Review: Printing and Comparing the Class Objects

This review explains the solution for the "printing and comparing objects'" exercise.

We'll cover the following...

Solution

Press + to interact
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. ...