Home > Enterprise >  Is it possible in python to add three instance variable using operator overloading like this s1 s2 s
Is it possible in python to add three instance variable using operator overloading like this s1 s2 s

Time:10-05

class user:
    def __init__(self):
        self.userid=int(input("Enter userid"))
        self.balance=float(input("Enter a balance"))
    def __add__(self,obj1,obj2):
        self.Totalbalance = self.balance   obj1.balance   obj2.balance
        print(self.Totalbalance)
    def __add__(self,obj1):

u1,u2,u3=user(),user(),user()
u1 u2 u3  #printing the result

CodePudding user response:

Not exactly, no. The __add__ method needs to take exactly two arguments; when you call it twice, you are basically doing

u1.__add__(u2).__add__(u3)

Also, your code doesn't do anything with the result.

There is nothing to stop a method from accepting three arguments, but the existing operators all take one (for unary minus, for example) or two arguments, and the general operator precedence dictates how they are going to get called.

Some other languages have ternary operators, for example the x ? y : z of C and many other languages (similar to y if x else z in Python); but making a ternary operator for something which already naturally decomposes into two binary operators seems like a needless complication.

CodePudding user response:

Here's how this would look, but this is still a bad idea. Please note that it is a very bad idea to have your general-purpose classes do their own I/O. The classes should encapsulate data and handle behavior on that data. I/O should be the responsibility of the caller.

class user:
    def __init__(self,userid=None,balance=None):
        self.userid=userid
        self.balance=balance
    def __add__(self,obj):
        return user(self.userid,self.balance obj.balance)


def newuser():
    userid=int(input("Enter userid "))
    balance=float(input("Enter a balance "))
    return user(userid,balance)


u1,u2,u3=newuser(),newuser(),newuser()
print((u1 u2 u3).balance)

Output:

Enter userid 1
Enter a balance 2
Enter userid 3
Enter a balance 4
Enter userid 5
Enter a balance 6
12.0

ALTERNATIVE

Another way to do this is to have user user return a float, then add a method that handles float user to do chaining. That's a little better, but it's still awkward:

class user:
    def __init__(self,userid=None,balance=None):
        self.userid=userid
        self.balance=balance
    def __add__(self,obj):
        return self.balance obj.balance
    def __radd__(self,obj):
        if isinstance(obj,user):
            return obj.balance self.balance
        if isinstance(obj,float):
            return obj self.balance


def newuser():
    userid=int(input("Enter userid "))
    balance=float(input("Enter a balance "))
    return user(userid,balance)


u1,u2,u3=newuser(),newuser(),newuser()
print(u1 u2 u3)

This produces the same output.

  • Related