+ 2

What does other mean in this code??

class Vector2D: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return Vector2D(self.x + other.x, self.y + other.y) first = Vector2D(5, 7) second = Vector2D(3, 9) result = first + second print(result.x) print(result.y) Im totally confused. Does "other" mean all other classes?

26th Jul 2016, 6:01 AM
Jason Ahn
10 odpowiedzi
+ 2
other means other object of class Vector2D you can't use + between classes result = first + second correct using is: result = first.__add__(second) in this case in function __add__ other.x means second.x
26th Jul 2016, 6:37 AM
Sweemyn
+ 1
nope, other is object of any class. see this example http://code.sololearn.com/cdThe2gTZ3WT . note that the code would break if you called a + 3 . since 3 is int which does not have val attribute.
26th Jul 2016, 7:01 AM
RedAnt
RedAnt - avatar
+ 1
oh, so you mean when there are more classes like vector 3D which has three objects, "other" will be any other objects including all three objects of Vector3D, right?
26th Jul 2016, 7:12 AM
Jason Ahn
0
so other means all other objects of Vector2D??
26th Jul 2016, 6:45 AM
Jason Ahn
0
yes, other is an instance of any other class or built in type, so if that class does not have x and y attributes, you will get exception. you can implement your __add__ method for only specific classes by checking class of other with isinstance. more about it here http://jcalderone.livejournal.com/32837.html
26th Jul 2016, 6:46 AM
RedAnt
RedAnt - avatar
0
hey but it worked same when i used "+" instead of __add__ is there any problem when using "+" instead of __add__?
26th Jul 2016, 6:52 AM
Jason Ahn
0
>>>so other means all other objects of Vector2D?? yes.
26th Jul 2016, 6:52 AM
Sweemyn
0
Hi Jason, You are right. It's very interesting - Python can search for built-in function using function name. I learned it just now. http://www.python-course.eu/python3_magic_methods.php
26th Jul 2016, 7:07 AM
Sweemyn
0
so if you know that first + second means first.__add__(second) You can understand very easy that in __add__(self, other) other it's your second class
26th Jul 2016, 7:11 AM
Sweemyn
0
Thank you guys ;)
26th Jul 2016, 7:15 AM
Jason Ahn