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())

Pesquisar
Categorias
Leia mais
Chemistry
UMTA UACE UMTA CHEMISTRY PAPER 1 2024 MOCKS
UMTA UACE CHEMISTRY PAPER 1 2024 MOCKS
Por Landus Mumbere Expedito 2024-08-01 16:10:54 0 4KB
Technology
Understanding the MOD Function
The MOD function in Excel is used to find the remainder after a number is divided by a divisor....
Por Microsoft Excel 2024-09-03 03:27:42 2 3KB
Biology
BIOLOGY ELEMENTS OF CONSTRUCT
BIOLOGY ELEMENTS OF CONSTRUCT
Por Landus Mumbere Expedito 2024-08-03 18:05:53 0 3KB
Gardening
Tips for Joining Football Betting Forums
Tips for Joining Football Betting Forums The world of online football betting is growing...
Por Hanoi Phoco 2024-12-11 03:57:59 0 2KB
Technology
Media and Software Piracy
Media and software piracy refer to the unauthorized copying, distribution, and use of digital...
Por ALAGAI AUGUSTEN 2024-07-13 07:52:56 0 3KB