Class Customization and Operator Overloading

0
12χλμ.

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

Αναζήτηση
Κατηγορίες
Διαβάζω περισσότερα
Technology
CSS - Styling Web Pages
Cascading Style Sheets (CSS) is a cornerstone technology of the World Wide Web, alongside HTML...
από ALAGAI AUGUSTEN 2024-07-26 17:44:53 0 20χλμ.
Physics
S.6 Physics 2 Facilitation 2024
https://acrobat.adobe.com/id/urn:aaid:sc:EU:fd4a0074-f4ff-48b8-9f7c-955b2dd2b3f2
από Landus Mumbere Expedito 2024-07-19 13:10:33 0 11χλμ.
Εκπαίδευση
ECONOMICS SOLUTIONS TO THE SEMINAR AT MAKERERE HIGH SCHOOL MIGADDE
ECONOMICS SEMINAR AT MAKERERE COLLEGE MIGADDE
από Landus Mumbere Expedito 2024-07-26 07:46:42 0 9χλμ.
Technology
HOW TO OVERCOME COMPUTER NETWORK CHALLENGES
Overcoming the challenges faced in managing and using computer networks requires a combination of...
από ALAGAI AUGUSTEN 2024-07-17 17:38:08 0 9χλμ.
Technology
Components of BIS: Hardware, Software, Data, People, Processes
Business Information Systems (BIS) are composed of several key components that work together to...
από Business Information Systems (BIS) Course 2024-07-31 18:24:21 0 10χλμ.
Tebtalks https://forum.tebtalks.com