pythonoperator-overloadingmagic-function

I Want to Know Why Magic Function Is Giving Specific Answer For Specific Operator


I was Using Magic Functions(Operator Overloading) In Python When I Came To Know that for a Specific Operator Python Is giving a Specific Answer

class over:
    def __init__(self,x):
        self.x=x
    def __add__(self,other):
        return over(self.x+other.x)
ob1=over(20)
ob2=over(30)
ob3=over(40)
ob4=ob1+ob2+ob3              #It Is adding All three
print(ob4.x)           # This Gave Me answer As 90

But When I Used Another Magic Function Such As Greater Then (gt) the It was Just Addinglast two Values namely ob2 and ob3

class over:
    def __init__(self,x):
        self.x=x
    def __gt__(self,other):
        return over(self.x+other.x)
ob1=over(20)
ob2=over(30)
ob3=over(40)
ob4=ob1>ob2>ob3     # This Is Just Adding Ob2 and Ob3
print(ob4.x)          #Result:70      

I want to Get Result 90 As I got it in my First Code, By using gt


Solution

  • Chaining for comparator operators happen bit different than +

    a < b < c
    

    is equivalent to

    a < b and b < c
    

    So your expression is actually being evaluated as:

    (ob1 < ob2) and (ob2 < ob3)
    

    Which gives

    over(x=70)
    

    Due to how the and operator works.

    To make the expression work you need to add some parentheses:

    (ob1 > ob2) > ob3
    

    Which gives:

    over(x=90)
    

    Ref: https://www.geeksforgeeks.org/chaining-comparison-operators-python/