Overloading of < and == operators

Overloading of < and == operators

Lesson Details:
June 29, 2020


I: Introduction

A: Learning basic python programming for beginners

Python is a high-level, general purpose, interpreted, interactive and object-oriented programming language. It was created by Guido van Rossum in the late 1980s.

It is a dynamic programming language that can be used to develop desktop applications, web applications, network applications, video games and so on. Python provides support for functional programming through lambda expressions, first-class functions and list comprehensions.

Python is a flexible language which can be used to create simple scripts or complex applications. It is an interpreted language, meaning that code is read by an interpreter rather than compiled into machine code beforehand.

Python has a simple syntax which makes it easy to learn. It also has fewer syntactical constructions than some other languages so new programmers are less likely to make mistakes.

Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles. Python features a dynamic type system and automatic memory management and has a large and comprehensive standard library.

Python is also extensible; users can add their own modules of pre-written code in C, C++ or python.

II: Body

A: Overloading of < and == operators

The relational operators >, >=, <, <= , != can be overloaded in python. If we want to compare two objects using these operators, the operands must support the operator overloading otherwise an exception will be thrown. The following example shows how they can be overloaded.

#!/usr/bin/python class MyString(str): def __init__(self, val): # __init__ method is called when the instance is created if val == "": # Check for empty string self.value = None else: self.value = val def __repr__(self): return "MyString('%s')" % self.value class MyNum(int): def __init__(self, val): # __init__ method is called when the instance is created if val == 0: self.value = None else: self.value = val def __repr__(self): return "MyNum('%s')" % self.value myNum = MyNum(10) myStr = MyString("Hello") if myNum < myStr>= myStr: print "myNum >= myStr" elif myNum <= myStr: print "myNum <= myStr" elif myNum != myStr: print "myNum != myStr" else: print "Match"













loader
Course content