Class Customization and Operator Overloading

0
12KB

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

Suche
Kategorien
Mehr lesen
Computer Programming
Dynamic Typing, Stubs, and Namespaces
Dynamic Typing: In Python, variables don't have a pre-defined data type associated with...
Ausbildung
Sharecropping in the Post-Civil War South
Von Modern American History 2024-07-19 06:00:38 0 11KB
Andere
Definition of Statistics
Statistics is a branch of mathematics that deals with collecting, analyzing, interpreting,...
Von Tebtalks Access 2024-07-12 19:44:34 0 21KB
Technology
Understanding Brute Force Attacks
A brute force attack is a method used by attackers to gain unauthorized access to a system,...
Von ALAGAI AUGUSTEN 2024-07-15 06:43:17 0 10KB
Biology
CAPILLARITY
How does capillary action work in plants? Capillary action in plants works through the...
Von Okiliong Peter 2024-09-04 13:04:49 0 19KB
Talksphare https://talksphare.com