Class Customization and Operator Overloading

0
4كيلو بايت

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

البحث
الأقسام
إقرأ المزيد
التعليم
S.4 CRE PRE-REGISTRATION 2024
https://acrobat.adobe.com/id/urn:aaid:sc:EU:21663e65-af20-41e8-b997-5def68c7399f
بواسطة Landus Mumbere Expedito 2024-07-19 23:19:32 0 3كيلو بايت
Physics
UCE PHYSICS PAPER 1 2024
UCE PHYSICS PAPER 1 2024
بواسطة Landus Mumbere Expedito 2024-08-01 16:23:47 0 3كيلو بايت
Technology
Increasing Pressure on IT Experts
Information technology (IT) experts face increasing pressure due to several factors that have...
بواسطة ALAGAI AUGUSTEN 2024-07-16 16:57:22 0 3كيلو بايت
Mathematics
UACE MATHS 1 WAKISSHA MARKING GUIDE
UACE MATHS 1 WAKISSHA MARKING GUIDE
بواسطة Landus Mumbere Expedito 2024-08-10 10:14:06 0 3كيلو بايت
التعليم
Timeline 1875-1890
1875 A Senate commission meeting with Red Cloud and other Lakota chiefs to negotiate legal...
بواسطة Modern American History 2024-08-02 16:29:08 0 3كيلو بايت