Class Customization and Operator Overloading

0
12كيلو بايت

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

البحث
الأقسام
إقرأ المزيد
Technology
Network topologies
Network topology refers to the arrangement of various elements (like nodes and links) in a...
بواسطة Mpatswe Francis 2024-10-03 22:58:40 0 10كيلو بايت
Technology
Scenarios of Computer Misuse and Their Effects on Society
Computer misuse can have widespread and serious impacts on society. It encompasses a wide range...
بواسطة ALAGAI AUGUSTEN 2024-07-13 07:42:14 0 10كيلو بايت
Biology
UACE BIOLOGY EDUCAN MOCK 2024
UACE BIOLOGY EDUCAN MOCK 2024
بواسطة Landus Mumbere Expedito 2024-08-11 11:48:05 0 10كيلو بايت
التعليم
Interactive Learning Boosts Retention by 75%
Did You Know? Interactive Learning Boosts Retention by 75%! Engage with Your Studies and See the...
بواسطة ALAGAI AUGUSTEN 2024-07-21 19:12:20 0 17كيلو بايت
Chemistry
A-LEVEL CHEMISTRY E.N RAMSDEN
A-LEVEL CHEMISTRY E.N RAMSDEN
بواسطة Landus Mumbere Expedito 2024-08-18 14:15:58 1 10كيلو بايت
Tebtalks https://forum.tebtalks.com