Class Customization and Operator Overloading

0
13KB

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

Suche
Kategorien
Mehr lesen
Physics
ASSHU ANKOLE MOCK S.6 PHYSICS PAPER 1 GUIDE 2024
ASSHU ANKOLE MOCK S.6 PHYSICS PAPER 1 GUIDE 2024
Von Landus Mumbere Expedito 2024-08-14 07:01:43 0 14KB
Ausbildung
Immigration timeline 1849-1924
1849: America’s first anti-immigrant political party, the Know-Nothing...
Von Modern American History 2024-08-02 16:41:54 0 12KB
Technology
The VLOOKUP function in Excel
The VLOOKUP function in Excel is used to search for a value in the first column of a table and...
Von Microsoft Excel Tips 2024-10-16 00:58:30 0 17KB
Chemistry
UMTA UACE CHEMISTRY PAPER 2 2024
UMTA UACE CHEMISTRY PAPER 2 2024
Von Landus Mumbere Expedito 2024-08-01 16:04:41 0 9KB
Business
Small Businesses: The Backbone of the Economy and Pillars of Community Growth
In the intricate fabric of our global economy, small businesses are the threads that hold it...
Von ALAGAI AUGUSTEN 2024-08-03 15:15:09 0 11KB
Talksphare https://talksphare.com