9. Operators - JulTob/Python GitHub Wiki
Here is the list of what you can command for custom classes:
Symbol | Dunder Method | Description |
---|---|---|
+a |
__pos__(self) |
Unary positive |
-a |
__neg__(self) |
Unary negation |
~a |
__invert__(self) |
Bitwise NOT |
abs(a) |
__abs__(self) |
Absolute value |
Symbol | Method | Reflected Method | Description |
---|---|---|---|
a + b |
__add__ |
__radd__ |
Addition |
a - b |
__sub__ |
__rsub__ |
Subtraction |
a * b |
__mul__ |
__rmul__ |
Multiplication |
a / b |
__truediv__ |
__rtruediv__ |
True Division |
a // b |
__floordiv__ |
__rfloordiv__ |
Floor Division |
a % b |
__mod__ |
__rmod__ |
Modulo |
a ** b |
__pow__ |
__rpow__ |
Exponentiation |
a << b |
__lshift__ |
__rlshift__ |
Left bitwise shift |
a >> b |
__rshift__ |
__rrshift__ |
Right bitwise shift |
a & b |
__and__ |
__rand__ |
Bitwise AND |
a ⎮ b |
__or__ |
__ror__ |
Bitwise OR |
a ^ b |
__xor__ |
__rxor__ |
Bitwise XOR |
🧙 Reflected methods (
__radd__
, etc.) are used when the left operand doesn’t know what to do with the right operand’s type.
Symbol | Method | Description |
---|---|---|
== |
__eq__ |
Equal |
!= |
__ne__ |
Not Equal |
< |
__lt__ |
Less than |
<= |
__le__ |
Less than or equal |
> |
__gt__ |
Greater than |
>= |
__ge__ |
Greater than or equal |
Symbol | In-place Method | Description | |
---|---|---|---|
+= |
__iadd__ |
In-place addition | |
-= |
__isub__ |
In-place subtraction | |
*= |
__imul__ |
In-place multiplication | |
/= |
__itruediv__ |
In-place division | |
//= |
__ifloordiv__ |
In-place floor division | |
%= |
__imod__ |
In-place modulo | |
**= |
__ipow__ |
In-place power | |
<<= |
__ilshift__ |
In-place left shift | |
>>= |
__irshift__ |
In-place right shift | |
&= |
__iand__ |
In-place bitwise AND | |
│= |
__ior__ |
In-place bitwise OR | |
^= |
__ixor__ |
In-place bitwise XOR |
Symbol / Usage | Method | Description | def |
---|---|---|---|
obj() |
__call__ |
Callable object | |
str(obj) |
__str__ |
User-facing string | |
repr(obj) |
__repr__ |
Debug/Dev string | |
len(obj) |
__len__ |
Length (e.g., for containers) | |
iter(obj) |
__iter__ |
Iterator start | |
next(obj) |
__next__ |
Iterator step | |
abs(obj) |
__abs__ |
Absolute value | |
complex(obj) |
__complex__ |
Convert to complex | |
int(obj) |
__int__ |
Convert to integer | |
float(obj) |
__float__ |
Convert to float | |
bool(obj) |
__bool__ |
Convert to boolean | |
hash(obj) |
__hash__ |
Hash for sets/dicts | |
obj = Class() | __init__ |
Initialize the object. | |
item in obj |
__contains__ |
Membership check (in ) |
|
obj[key] |
__getitem__ |
Indexing | def __getitem__(obj, key): |
obj[key] = val |
__setitem__ |
Item assignment | def __setitem__(obj, key, val): |
del obj[key] |
__delitem__ |
Item deletion | def __delitem__(obj, key): |
Operation | Syntax | Method |
---|---|---|
Addition | a + b | add |
Subtraction | a - b | sub |
Multiplication | a * b | mul |
Division | a / b | truediv |
Floor Division | a // b | floordiv |
Modulo | a % b | mod |
Power | a ** b | pow |
Negation | -a | neg |
Positive | +a | pos |
Absolute | abs(a) | abs |
These be keywords and control flows:
-
and
,or
,not
— ❌ -
is
,is not
— ❌ (identity) -
if
,else
,while
,for
— ❌ -
in
(can override via__contains__
only) -
await
,async
,yield
— ❌
Note: It is not possible to change the number of operands of an operator. For example: If we can not overload a unary operator as a binary operator. The following code will throw a syntax error.
It is not possible to change the number of operands of an operator. For example: If we can not overload a unary operator as a binary operator. The following code will throw a syntax error.
Ahoy! What a fine trove of treasure ye’ve unearthed—a ledger of Python’s operator magics and mystic methods! 🧙♂️⚓
Let me now take yer draft and polish it into a full and accurate Ledger_of_OperatorOverloads—complete, categorized, and clear as a compass star.
Symbol | Dunder Method | Description |
---|---|---|
+a | pos(self) | Unary positive |
-a | neg(self) | Unary negation |
~a | invert(self) | Bitwise NOT (or logical NOT in custom logic) |
Operator overloading in Python allows custom classes to define or redefine the behavior of standard operators. This is achieved by implementing special methods, commonly known as "dunder" (double underscore) methods.
-
Reflected Methods: Methods like
__radd__
,__rsub__
, etc., are called when the left operand does not support the operation and the operands are of different types. -
In-place Methods: Methods like
__iadd__
,__isub__
, etc., are used for in-place operations (e.g.,a += b
). If not defined, Python falls back to the regular method (e.g.,__add__
) and assigns the result to the variable. -
Not All Operators Are Overloadable: Logical operators like
and
,or
, andnot
cannot be overloaded directly. However, you can achieve similar behavior by overloading__bool__
and using bitwise operators (&
,|
,~
) as substitutes.
May this guide serve ye well on your coding voyages! Should ye desire further assistance or examples, don't hesitate to summon me.