Arithmetic operator overloading of python
What is operator overloading
In fact, "operator overloading" only means to intercept the built-in operation in the class method. When the class instance appears in the built-in operation, Python automatically calls your method, and the return value of your method becomes the result of the corresponding operation. The following is a review of the key concepts of overloading:
- Operator overloading lets classes intercept regular Python operations.
- Class overloads all Python expression operators
- Class can overload built-in operations such as printing, function call, attribute point number operation, etc
- Overloading makes class instances behave like built-in types.
- Overloading is implemented through class methods with special names.
Overloading of arithmetic operators
**Overloaded table of arithmetic operators:**
Method name | Operators and Expressions | explain |
---|---|---|
__add__(self,other ) | self + other | addition |
__sub__(self,other ) | self - other | subtraction |
__mul__(self,other ) | self * other | multiplication |
__truediv__(self,other ) | self / other | division |
__floordiv__(self,other ) | self //other | to be divisible by |
__mod__(self,other ) | self % other | Mold taking (remainder) |
__pow__(self,other ) | self **other | exponentiation |
Overload of inverse operator
When the left side of the operator is a built-in type and the right side is a user-defined type, a TypeError error will appear when arithmetic uniform operator operation is performed, because the code of the built-in type cannot be modified. At this time, the overload of the reverse operator needs to be used.
Overloaded table of inverse arithmetic operators:
Method name | Operators and Expressions | explain |
---|---|---|
__radd__(self,other) | other + self | addition |
__rsub__(self,other) | other - self | subtraction |
__rmul__(self,other) | other * self | multiplication |
__rtruediv__(self,other) | other / self | division |
__rfloordiv__(self,other) | other // self | to be divisible by |
__rmod__(self,other) | other % self | Mold taking (remainder) |
__rpow__(self,other) | other ** self | exponentiation |
Overloading of compound assignment arithmetic operators
The compound assignment arithmetic operator takes x += y as an example, and this operator will call x first__ iadd__ (y) Method, if not__ iadd__ When the method is used, the compound assignment arithmetic operation is disassembled into: x = x + y, and then x = x.__add__(y) Method, if it no longer exists__ add__ Method, an error exception of type TypeError will be triggered.
**Overloaded table of compound assignment arithmetic operators:**
Method name | Operators and Expressions | explain |
---|---|---|
__iadd__(self,other) | self += other | addition |
__isub__(self,other) | self -= other | subtraction |
__imul__(self,other) | self *= other | multiplication |
__itruediv__(self,other) | self /= other | division |
__ifloordiv__(self,other) | self //=other | Floor except |
__imod__(self,other) | self %= other | Mold taking (remainder) |
__ipow__(self,other) | self **=other | exponentiation |
Overloading of comparison arithmetic operators
**Overloaded table of comparison arithmetic operators:**
Method name | Operators and Expressions | explain |
---|---|---|
__lt__(self,other) | self < other | less than |
__le__(self,other) | self <= other | Less than or equal to |
__gt__(self,other) | self > other | greater than |
__ge__(self,other) | self >= other | Greater than or equal to |
__eq__(self,other) | self == other | be equal to |
__ne__(self,other) | self != other | Not equal to |
example:
class Fraction: "fraction" def __init__(self, molecularK: int, denominator: int = None): if not (isinstance(molecularK, int) and isinstance(denominator, int)): raise TypeError("expect int") if denominator == None: self.integer = molecularK elif molecularK == denominator: self.integer = 1 else: reduction = self.gcd(molecularK, denominator) self.num = molecularK // reduction self.den = denominator // reduction def __str__(self): # When rewriting the str method, you can't use print. You need to use return. Change it to the following code form to stop reporting errors return str(self.num) + "/" + str(self.den) def __add__(self, other): if self.den == other.den: new_num = self.num + other.num return Fraction(new_num, self.den) else: new_den = self.den * other.den new_num = (self.num * other.den) + (other.num * self.den) return Fraction(new_num, new_den) def __sub__(self, other): "-" if self.den == other.den: new_num = self.num - other.num return Fraction(new_num, self.den) else: new_den = self.den * other.den new_num = (self.num * other.den) - (other.num * self.den) return Fraction(new_num, new_den) def __mul__(self, other): "*" new_num = self.num * other.num new_den = self.den * other.den return Fraction(new_num, new_den) def __truediv__(self, other): "/" new_num = self.num * other.den new_den = self.den * other.num return Fraction(new_num, new_den) def __gt__(self, other): ">" first = self.num * other.den two = self.den * other.num return first > two def __ge__(self, other): ">=" first = self.num * other.den two = self.den * other.num return first >= two def __lt__(self, other): "<" first = self.num * other.den two = self.den * other.num return first < two def __le__(self, other): "<=" first = self.num * other.den two = self.den * other.num return first <= two def __ne__(self, other): "!=" first = self.num * other.den two = self.den * other.num return not first == two def __eq__(self, other: object) -> bool: "==" first = self.num * other.den two = self.den * other.num return first == two def gcd(self, a, b): """Rolling phase division """ if a < b: a, b = b, a return a if b == 0 else self.gcd(b, a % b) def get_num(self): return self.num def get_den(self): return self.den sample = Fraction(4, 5) sample1 = Fraction(6, 9) print(sample + sample1) print(sample - sample1) print(sample * sample1) print(sample / sample1) print(sample > sample1) print(sample >= sample1) print(sample < sample1) print(sample <= sample1) print(sample != sample1) print(sample == sample1) # =========== print =========== 22/15 2/15 8/15 6/5 True True False False True False
Unfinished to be continued