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

Rechercher
Catégories
Lire la suite
Éducation
ECONOMICS DISCUSSION QUESTIONS
ECONOMICS DISCUSSION QUESTIONS
Par Question Bank 2024-08-26 05:07:49 0 13KB
Chemistry
MARKING GUIDE FOR UMTA UCE CHEMISTRY PAPER 1 2024
MARKING GUIDE FOR UMTA UCE CHEMISTRY PAPER 1 2024
Par Landus Mumbere Expedito 2024-08-19 20:56:42 0 11KB
Chemistry
UACE CHEMISTRY PAPER 1
UACE CHEMISTRY PAPER 1
Par Landus Mumbere Expedito 2024-08-09 19:49:58 0 11KB
Autre
Clear the Clutter
 A Word of Encouragement Life is a journey filled with ups and downs, triumphs and...
Par ALAGAI AUGUSTEN 2024-08-10 12:44:57 0 11KB
Éducation
Business Information Systems Course Outline
Introduction to Business Information Systems Overview of BIS Importance of BIS in modern...
Par Business Information Systems (BIS) Course 2024-07-30 18:16:52 0 14KB
Talksphare https://talksphare.com