+ 2
Overloading in Python
I have stumbled on one question in SoloLearn's quizzes. I know how overloading is working in Python and I understand how it changes built-ins. But I don't understand this code: class wow: def __init__(s,x): s.x=x def __add__(s,y): return wow(s.x - x.y) def __sub__(s,y): return wow(s.x + x.y) def __repr__(s): return str(s.x) a = wow(5) b = wow(7) c = wow(3) OK. s = self. I know that only position is important, not it's name. But how we use wow's __init_ in the overloading if 'y' is not defined? And what does this 'x.y' means? I thought we need to define 'y' before defining overloading. Please, help to understand it.
1 Odpowiedź
+ 2
First of all, you incorrectly copied the question.
in __add__ it should be y.x rather than x.y.
so + overloading works as below.
a+b is a.__add__(b). where a and b are both objects of the same type.
def __add__ (s,y): should be read as __add__(self,other)
return self. x - other.x
in other words it just overload + with -