Class Customization and Operator Overloading

0
11Кб

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

Поиск
Категории
Больше
Другое
Israeli Defense Minister Cancels Visit with Pentagon Chief Amid Rising Tensions
Tel Aviv, October 9, 2024 – In a significant development, Israeli Defense Minister...
От Updates & History 2024-10-09 17:53:53 0 12Кб
Computer Programming
HTML Table Sizes: Controlling Dimensions
HTML tables can be sized using the width and height attributes, which specify the dimensions of...
От HTML PROGRAMMING LANGUAGE 2024-09-06 01:29:20 0 10Кб
Computer Programming
Programming basics
Computer programs are used by people every day. Everytime you use your smartphone, tablets, and...
Technology
Executive Information Systems (EIS)
Executive Information Systems (EIS) are specialized information systems designed to support the...
От Business Information Systems (BIS) Course 2024-08-01 17:01:05 0 9Кб
Tebtalks https://tebtalks.com