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
Nach Verein filtern
Read More
Chemistry
S.4 CHEMISTRY WAKATA PRE MOCK QUESTIONS 2
https://acrobat.adobe.com/id/urn:aaid:sc:EU:85bd6cfc-45b5-4737-b430-d0e1fce698e9
Von Landus Mumbere Expedito 2024-07-19 23:27:53 0 3KB
Ausbildung
Black Codes and Segregation in Reconstruction
Black Codes: The Black Codes were a series of laws passed by Southern states after the Civil...
Von Modern American History 2024-07-19 05:43:15 0 3KB
Technology
Popular Linux Distributions
Linux distributions, or distros, come in various forms tailored to different user needs, ranging...
Von Tebtalks Access 2024-07-13 07:29:49 0 3KB
Business
Build Meaningful Connections and Watch Your Business Thrive
Networking is Key! Build Meaningful Connections and Watch Your Business Thrive In the fast-paced...
Von ALAGAI AUGUSTEN 2024-07-23 17:42:22 0 5KB
Computer Programming
Range and Nested Loops
Range Function (range()) The range() function is a built-in function in Python used to generate...