Class Customization and Operator Overloading

Class customization

Class customization allows you to define how a class behaves for specific operations such as printing or accessing attributes.

Customize classes by creating instances methods using special method names (double underscores).

Rich comparison methods overload some common comparison operators.

Rich comparison method

Overloaded operator

__lt__(self, other)

Less than (<)

__le__(self, other)

Less than or equal-to (<=)

__gt__(self, other)

Greater than (>)

__ge__(self, other)

Greater than or equal-to (>=)

__eq__(self, other)

Equal to (==)

__ne__(self, other)

Not equal to (!=)

 

Operator overloading

Operator Overloading allows you to replace the functionality of numeric operators (such as +, -, *, and /) with a method.

For example, you can write an __add__(self, other) method to replace the functionality of the (+) operator.

Use the built-in isinstance() method to handle different object types for the operation.

Method

Description

__add__(self, other)

Add (+)

__sub__(self, other)

Subtract (-)

__mul__(self, other)

Multiply (*)

__truediv__(self, other)

Divide (/)

__floordiv__(self, other)

Floored division (//)

__mod__(self, other)

Modulus (%)

__pow__(self, other)

Exponentiation (**)

__and__(self, other)

"and" logical operator

__or__(self, other)

"or" logical operator

__abs__(self)

Absolute value (abs())

__int__(self)

Convert to integer (int())

__float__(self)

Convert to floating point (float())

Search
Categories
Read More
Education
Immigration timeline 1849-1924
1849: America’s first anti-immigrant political party, the Know-Nothing...
By Modern American History 2024-08-02 16:41:54 0 3K
Games
कोलकाता फटाफट: एक गहन जानकारी
कोलकाता फटाफट: क्यों है खास?  कोलकाता फटाफट की खासियत इसकी सरलता और समय की पाबंदी है। यह...
By Karthik Bose 2024-12-17 12:05:26 0 335
Computer Programming
Lists, List Methods, and List Iteration
Lists are a fundamental data structure in Python used to store ordered collections of items. They...
Education
UACE WAKISSHA FOODS AND NUTRITION 2024
UACE WAKISSHA FOODS AND NUTRITION 2024
By Landus Mumbere Expedito 2024-08-10 10:19:35 0 3K
Education
Adapting to the Digital Age in Education
From Classrooms to Virtual Spaces: Adapting to the Digital Age in Education The landscape of...
By ALAGAI AUGUSTEN 2024-07-21 19:24:04 0 4K