Magic Methods 2
Magic Methods 2: Mathematical Calculation P1
int, float, string, tuple, list… -> Factory Function
1 |
|
An example of magic methods. In this example, we make the add and subtract reciprocated.
1 |
|
Some bugs we need to pay attention to! Otherwise we may come across infinite iteration.
1 |
|
The code can be fixed as below:
1 |
|
Here is the introduction of magic methods that is for calculation.
Calculation Operators
Magic Methods | Function |
---|---|
__add__(self, other) | ‘+‘ |
__sub__(self, other) | ‘-‘ |
__mul__(self, other) | ‘*‘ |
__truediv__(self, other) | ‘/‘ |
__floordiv__(self, other) | ‘//‘ |
__mod__(self, other) | ‘%’ |
__divmod__(self, other) | ‘divmod()’ |
__pow__(self, other[,modulo]) | ‘**‘ |
__lshift__(self, other) | ‘<<’ |
__rshift__(self, other) | ‘>>’ |
__and__(self, other) | ‘bit and: &‘ |
__xor__(self, other) | ‘bit xor: ^‘ |
__or__(self, other) | ‘bit or: |’ |
mod() 取模(余数)
divmod(a, b) -> (a//b, a%b)
1 byte = 8 bit
3 == 00000011 -> << -> 00000110
####reverse calculation
When the first cannot do the calculation, then let the latter do it. We need to know that self is the latter, other is the first, if we do the reverse calculation. Here the reverse magic methods is the ‘r’ + ‘magic name’, just as __radd__(self, other).
1 |
|
For those operations that attach importance to sequence. We need to be careful.
1 |
|
####Augmented assignment
Here the reverse magic methods is the ‘i’ + ‘magic name’, just as __iadd__(self, other). The meaning is self+=other.
####Unary operator
Magic Methods | Function |
---|---|
__neg__(self) | ‘-x’ |
__pos__(self) | ‘+x’ |
__abs__(self) | ‘abs(x)’ |
__invert__(self) | ‘~x : Bit (0 <-> 1)’ |
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!