python arithmetic operator overloading

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 nameOperators and Expressions explain
__add__(self,other )self + otheraddition
__sub__(self,other )self - othersubtraction
__mul__(self,other )self * othermultiplication
__truediv__(self,other )self / otherdivision
__floordiv__(self,other )self //otherto be divisible by
__mod__(self,other )self % otherMold taking (remainder)
__pow__(self,other )self **otherexponentiation

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 nameOperators and Expressions explain
__radd__(self,other)other + selfaddition
__rsub__(self,other)other - selfsubtraction
__rmul__(self,other)other * selfmultiplication
__rtruediv__(self,other)other / selfdivision
__rfloordiv__(self,other)other // selfto be divisible by
__rmod__(self,other)other % selfMold taking (remainder)
__rpow__(self,other)other ** selfexponentiation

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 nameOperators and Expressions explain
__iadd__(self,other)self += otheraddition
__isub__(self,other)self -= othersubtraction
__imul__(self,other)self *= othermultiplication
__itruediv__(self,other)self /= otherdivision
__ifloordiv__(self,other)self //=otherFloor except
__imod__(self,other)self %= otherMold taking (remainder)
__ipow__(self,other)self **=otherexponentiation

Overloading of comparison arithmetic operators

**Overloaded table of comparison arithmetic operators:**

Method nameOperators and Expressions explain
__lt__(self,other)self < otherless than
__le__(self,other)self <= otherLess than or equal to
__gt__(self,other)self > othergreater than
__ge__(self,other)self >= otherGreater than or equal to
__eq__(self,other)self == otherbe equal to
__ne__(self,other)self != otherNot 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

Tags: Python

Posted on Mon, 22 Nov 2021 14:30:18 -0500 by chuddyuk