+ 3

😐Explain me this question😐

This is a question of python challenge which I am not able to answer: class wow: def__init__(s,x): s.x = x def__add__(s,y): return wow(s.y - y.x) def__sub__(s,y): return wow(s.x + y.x) def__repr__(s): return str(s.x) a = wow(5) b = wow(7) c = wow(3) print(a-b+c) Please, help me to know the solution Thanks for your solutions !

10th Nov 2017, 6:32 AM
#RahulVerma
#RahulVerma - avatar
5 odpowiedzi
+ 3
Let's go through this step by step: a = wow(5) What this step does is to create an instance of the class called "a" with an "x" value of 5. b = wow(7) Similarly, another instance is created with an "x" value of 7. c = wow(3) Same thing. print (a-b+c) What is a-b? This is not defined usually (you can't just subtract instances of classes) but as the "-" operator is overloaded in the class, this is instead defined by the user. Take a look at this line: def __sub__(s, y): return wow(s.x - y.x) Rather misleadingly, this line says that when "adding" instances of classes together, subtract their "x" value by the other instance's "x" value. Hence, a-b = a's "x" value + b's "x" value = 12. Similarly for "+", the plus operator now subtracts the second "x" value from the first "x" value, hence (a-b) (which has an "x" value of 12) - c = 9. Hence, the answer is 9. (BTW, the __repr__ is used to return a printable representation of the object.)
10th Nov 2017, 6:57 AM
blackcat1111
blackcat1111 - avatar
+ 4
This effect was treaten in python course as "magic words" . it was not ment kidding python learners. The usual usecase for that is to use common operators for all objects if wanted. Anyhow this challenge opened my eyes.
10th Nov 2017, 7:52 AM
Oma Falk
Oma Falk - avatar
+ 2
@ blackcat1111 Thanks for giving me such a wonderful explanation !
10th Nov 2017, 7:04 AM
#RahulVerma
#RahulVerma - avatar
+ 2
Welcome! 🙂
10th Nov 2017, 7:09 AM
blackcat1111
blackcat1111 - avatar
+ 1
__add__ overrides + operator of wow objects __sub__ overrides - operator of wow objects __mul__ overrides * operator of wow objects. And so on. Hence they profuce a different value with the initialized values due to the altered operators
10th Nov 2017, 8:24 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar