Oop – Python Equivalent of Java’s Compareto()

OOP PYTHON EOUIVALENT OF JAVA'S COMPARETO(

Python and Java are two of the most common programming languages in today’s time. Programmers never stick to one language, they constantly have to change languages for the sake of development. Every new project may have different requirements. So often, people start with one language and then switch to another and try to understand every aspect of it in reference to the language they already know.

If you’re a Java user and have just started Python, you may wonder if there is a function similar to the Compareto() method of Java. Everything is minimalistic in Python, unlike Java which is completely OOP (Object Oriented Programming) based. You may be thinking, there’s no way Python would have as many functionalities as Java. But let me tell you, Python is no less when it comes to functionalities.

Python is also an Object Oriented Programming language and is not short on functionalities. In this article, we will see how we can do object-oriented programming in Python and check out some Java methods in Python.

What is Object Oriented Programming?

Object-oriented programming is a method of programming where you create classes and objects which consists of the member functions and data members instead of creating procedures or normal functions. A class enwraps data members, and the member functions together, and an object is just an instance of this class.

Related: Object-oriented programming in Python.

Properties of Object-Oriented Programming

The properties of object-oriented programming are:

  • Encapsulation – binding member functions and data members together.
  • Abstraction – Hiding the details.
  • Inheritance – Following the DRY (Don’t repeat yourself) rule. Inheriting properties of one class into another.
  • Polymorphism – One interface multiple forms.

How to create a class in Python?

You can create a class in Python using the ‘class‘ keyword.

class <class-name>:
    #class members goes here

What’s the Compareto() method in Java?

The Compareto() method is used to set the comparison logic between two objects of the same class for sorting or other purposes where we need to compare two objects of the same class.

It is part of the "Comparable" interface of the "java.lang" package. You can override the comparison logic of the class of objects using "@override".

It is most commonly used to compare strings. It makes working on strings a lot easier. Let’s see how it is done on strings.

class Main {
  public static void main(String[] args) {
    System.out.println("Welcome to".compareTo("AskPython")); 
  }
}

OUTPUT
22

In the above block of code, we have the main class and then the main function in it, which is supposed to be compiled. We have the string “Welcome to” which we then compare with the “AskPython” string. When we compare two strings with the compareto() method, it compares the ASCII (American Standard Code for Information Interchange) of the first character. If the ASCII value of the first character is the same, it compares the ASCII value of the second character, and so on.

“A” is smaller than “W”, so the difference between them will be positive. The ASCII value of “W” is 87, and the ASCII value of “A” is 65. So the difference will be 22. Hence, the output is 22.

Now, how can we do this in Python?

Python doesn’t have any method to get the exact difference between two strings, but it has methods to check if two strings are equal, less than, or greater than.

print("b"<"a")
String Compare
String Compare

If you want to get the difference between the ASCII values, just like the compare_to method of Java, you can simply create a custom function for it.

Let’s see how we can do it.

def compare_to(str1, str2):
    for i in range(min(len(str1), len(str2))):
        diff = ord(str1[i]) - ord(str2[i])
        if diff != 0:
            return diff
   
    return len(str1) - len(str2)
compare_to("Welcome to","AskPython")
Python Equivalent Of Javas Compareto
Python Equivalent Of Javas Compareto

In the above block of code, we created a function compare_to which is supposed to do the same as Java’s compareto() method. So for this, we looped through the entire string1 and string2, and for each character, we checked if they were equal, and if they were not, we’d calculate the difference between them.

Now Java’s compareTo() method allows you to compare any class, not just string, by overriding the compareto() method using @override. There’s a way in Python to do the same thing.

Magic or dunder methods

Magic methods are methods with double leading and double trailing underscores. They’re pre-defined member functions of class that can manipulate the behavior of different in-built methods of Python.

Related: Learn more about the magic and dunder methods.

There are magic methods in Python that manipulate the less than, greater than, equal to, and not equal to operators and their working for each class of data.

Let’s see how we do it for our custom class "human" and compare humans based on their age.

class Human:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def __lt__(self, other):
        return self.age < other.age
    def __gt__(self, other):
        return self.age > other.age
    def __eq__(self, other):
        return self.age == other.age
    def __ne__(self, other):
        return self.age != other.age

We created the class "Human" and gave it data members – name and age. Now we set up their __lt__, __gt__, __eq__, __ne__ dunder methods.

Now that we’re done with setting up everything let’s test it.

We’ll create two "Human" objects, ‘h1’ and ‘h2’.

h1 = Human("Kundan", 19)
h2 = Human("Rohan", 21)

Now let’s compare them and print who’s older and who’s younger.

if h1 < h2:
    print(h1.name + " is younger than " + h2.name)
elif person1 > person2:
    print(h1.name + " is older than " + h2.name)
else:
    print(h1.name + " and " + h2.name + " are of the same age.")
Lt Gt Eq Ne Dunder Methods
Lt Gt Eq Ne Dunder Methods

Applications of the compareto() method

It is an essential method for any class. Especially if we want to make it sortable. We need to be able to compare two objects of the same class. Setting up the magic methods of any class is not only a good practice but a necessary practice. Now if we would need to sort an array of humans, it would be a matter of a single line of code.

Sorting an array of humans based on their age

humans = [
    Human("Kundan", 19),
    Human("Rohan", 21),
    Human("Rahul", 22),
    Human("Ravi", 15),
    Human("Satyam", 16)
]
print("Unsorted humans:")
for human in humans:
    print(human.name)
#sorting the humans array with key as their age
humans.sort(key= lambda human:human.age)
print("\nSorted humans:")
for human in humans:
    print(human.name)
Sorting User Defiend Class
Sorting User-Defined Class

Conclusion

Switching languages can be a hard task. It’s necessary to know the ins and outs of the language which you’re trying to use. Learning a new language is a lot harder than we think. These small things that shouldn’t take time usually prove to be the most time-consuming. Stuff like this is not hard, we just don’t know some basic facts. And these problems can’t be solved until we get to know these facts. And this part is really hard.

The key to anything related to programming is always practice. It is the same with learning a new language. You won’t get good until you practice enough. Make sure to actually get your hands dirty and learn and practice as many new things as you can.

References

Official Python Documentation.

Stack Overflow answer for the same question.