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

Pesquisar
Categorias
Leia Mais
Physics
MATIGO PHYSICS PAPER 1 2024
MATIGO UACE PHYSICS PAPER 1 2024
Por Question Bank 2024-09-05 17:26:27 0 12K
Educação
Steps to Write a Best CV
A well-crafted CV is essential for making a positive impression on potential employers. Here are...
Por Mpatswe Francis 2024-08-31 18:31:33 2 9K
Computer Programming
Global attributes (id, class, style, title)
Global attributes are attributes that can be applied to any HTML element. They provide additional...
Por HTML PROGRAMMING LANGUAGE 2024-08-15 01:29:55 0 7K
Outro
Israeli Defense Minister Cancels Visit with Pentagon Chief Amid Rising Tensions
Tel Aviv, October 9, 2024 – In a significant development, Israeli Defense Minister...
Por Updates & History 2024-10-09 17:53:53 0 12K
Computer Programming
Italic Text in HTML: <i> and <em>
To make text italic in HTML, you can use either the <i> or <em> element. Both...
Por HTML PROGRAMMING LANGUAGE 2024-08-29 01:53:32 0 7K
Tebtalks https://tebtalks.com