Exercise: Printing and Comparing the Class Objects

Let’s try to print a string representation of a class object's contents and compare these objects.

We'll cover the following

Problem statement

You have been provided a Person class with the variables name and age.

One of your tasks is to add a __str__() function to the Person class to be able to print the contents of your object. Your function should print the name and age variables of the Person class, like “Josh is 25 years old”.

You also need to implement the __eq__, __lt__, and __ge__ functions in your Person class, in which you will compare the purchases of each person.

Input

class Person(object):
  def __init__(self, name, age, purchases):
    self.name = name
    self.age = age
    self.purchases = purchases

Output

Note: In the following example, the functions haven’t been filled. They’re just to give you an idea of what your Person class should look like.

class Person(object):
  def __init__(self, name, age, purchases):
    self.name = name
    self.age = age
    self.purchases = purchases

  def __str__(self):

  def __eq__(self, person):

  def __lt__(self, person):

  def __ge__(self, person):

Challenge

This problem has been designed for you to practice freely, so try to solve it on your own first. Take some time and think about the different concepts that we’ve explored in the course so far.

If you feel stuck, you can always check out the solution review provided in the next lesson.

Good luck!

Get hands-on with 1400+ tech skills courses.