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
Computer Programming
Floating-Point Numbers and Arithmetic Expressions
Floating-point numbers A floating-point number is a number with a decimal. Ex: 3.14,...
Technology
Role of Business Information Systems (BIS) in Various Business Functions
Business Information Systems (BIS) play a crucial role in enhancing the efficiency and...
Por Business Information Systems (BIS) Course 2024-08-01 17:02:21 0 4K
Technology
Understanding the ROUND Function
The ROUND function in Excel is used to round a number to a specified number of decimal places....
Por Microsoft Excel 2024-09-03 03:30:30 0 3K
Technology
Understanding Information Technology Ethics
Information Technology (IT) ethics is a branch of ethics that focuses on the ethical issues and...
Por ALAGAI AUGUSTEN 2024-07-13 07:12:07 0 3K
Business
Running a Successful Business
Beyond Profits to Building a Strong Foundation In the world of business, success is often...
Por ALAGAI AUGUSTEN 2024-08-03 15:49:40 0 3K