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
Politics
Putin in Mongolia, no arrest made - ablow to ICC
Russian President Vladimir Putin recently visited Mongolia, marking his first trip to a member...
By Patswe 2024-09-03 20:32:28 0 4K
Computer Programming
Class Customization and Operator Overloading
Class customization Class customization allows you to define how a class behaves for...
Other
Know Your Worth, Control Your Emotions, and Never Settle
In a world that often pushes us to conform, understanding your value, mastering your emotions,...
By Olaim 2024-08-14 05:42:34 0 4K
Education
S4 CHEMISTRY
https://acrobat.adobe.com/id/urn:aaid:sc:EU:c0424112-e1de-4038-84a6-6743ec084d39
By Expedito 2024-07-24 19:24:46 0 4K
Technology
Understanding Web Frameworks and Libraries
Understanding Web Frameworks and Libraries In the world of web development, efficiency and...
By Olaim 2024-07-26 17:50:40 0 8K