0

I have a problem where I need to sort a list of objects by the values of one of its members.

Example.py

class Example:

    def __init__(self, number, kind, amount):
        self.number = number
        self.kind = kind
        self.amount = amount

    def get_number(self):
        return self.date

    def get_kind(self):
        return self.kind

    def get_amount(self):
        return self.amount

Say I create an empty list and then append a few Example objects. This isn't exactly how I am doing it but for the sake of this question lets do it like so:

list_of_objects = []

a = Example(0, "test", 10)
b = Example(5, "test", 11)
c = Example(28, "test", 10)
d = Example(16, "test", 10)
e = Example(2, "test", 10)
f = Example(1, "test", 10)
list_of_objects.append(a)
list_of_objects.append(b)
list_of_objects.append(c)
list_of_objects.append(d)
list_of_objects.append(e)
list_of_objects.append(f)

Then, I need to take this list in a sort function that creates a new sorted list. This new list needs to only be sorted by the values of the first member variable (e.g. self.number). After this, it should print the sorted objects and each of their member variables like so.

 0:test:10
 1:test:10
 2:test:10
 5:test:11
 16:test:10
 28:test:10

1 Answers1

0

Have a quick look about dunder methods and see how you can implement the lt (lower than) or gt (greater than) for your class. After doing that, you will be able to create a list of such objects and just say list_of_objects.sort() and it will work.

To implement a dunder method simply add a new method in your class like this:

class Example:

    def __init__(self, number, kind, amount):
        self.number = number
        self.kind = kind
        self.amount = amount

    def get_number(self):
        return self.date

    def get_kind(self):
        return self.kind

    def get_amount(self):
        return self.amount

    def __lt__(self, other):
       return self.ATTRIBUTE_YOU_WANT < other.ATTRIBUTE_YOU_WANT