+ 1

overloading the + operator outside of a class

Is this sort of thing possible (see code below) . More interested in the overloading part rather than just the ability to add the list together. (I've done something similar C++ no problem) def __add__(self, obj): temp = [] temp[0] = self[0] + obj[0] temp[1] = self[1] + obj[1] return temp list1 = [10, 10] list2 = [10, 10] print(list1 + list2) # want output to be [20, 20] here a simple example but in c++: #include <iostream> using namespace std; class person{ public: int intA; int intB; person(int a, int b){ intA = a; intB = b; } }; //########################### int operator+(int total, person &obj){ //## <-how do you do this sort of thing? return total + obj.intA + obj.intB; } //########################## int main() { person rod(20, 20); int a = 20 + rod; cout << a << endl; return 0; }

30th Sep 2019, 9:03 PM
rodwynnejones
rodwynnejones - avatar
4 Respostas
+ 2
ahh and now i can do this (sort of does what i was thinking of) class MyInt(int): def __init__(self, num): super().__init__() self.num = num def __add__(self, mylist): return sum(mylist) + self.num mynum = MyInt(20) mylist = [1, 2, 3, 4, 5] print(mynum + mylist)
30th Sep 2019, 10:46 PM
rodwynnejones
rodwynnejones - avatar
+ 2
class MyList(list): def __init__(self, val): self.val = val self.length = len(self.val) def __add__(self, other): newlst = [] for ind in range(max(self.length, other.length)): n = 0 if ind < self.length: n += self.val[ind] if ind < other.length: n += other.val[ind] newlst.append(n) return newlst lst1 = MyList([10,10]) lst2 = MyList([1,2]) lst3 = MyList([3]) print(lst1+lst1) # [20, 20] print(lst2+lst3) # [4, 2]
1st Oct 2019, 5:08 AM
Diego
Diego - avatar
+ 1
Thanks for the tip HonFu... had a go and came up with this (please see comments on last line though) class Mylist(list): def __init__(self, obj): super().__init__() self.list_total = sum(obj) def __add__(self, start): return self.list_total + start mylist1 = Mylist([1, 2, 3, 4, 30]) print(mylist1 + 10) # < this works but... # print(10 + mylist1) # < this woun't.
30th Sep 2019, 10:30 PM
rodwynnejones
rodwynnejones - avatar
0
I think, in Python, magic methods (operator overloads) are always class-based. But you can try to create your own list type by inheriting, and see if you can overwrite the add method. class MyList(list): def __add__(self, other): # and so on If you try, give me a call, I'd like to see the result! :)
30th Sep 2019, 9:58 PM
HonFu
HonFu - avatar