0
Program misunderstanding problem
class Vec: def __init__(self, x, y): self.x=x self.y=y def __add__(self, ob): res=Vec(self.x-ob.x, self.y-ob.y) return res first=Vec(5,9) secound=Vec(3,9) result=first+secound print(result.y) >>> 0 >>> I know the answer, but I don't understand what is ob.x and ob.y. Is it the same to self.x/y in this code or what is it?
5 odpowiedzi
+ 3
The __add__ method defines what happens if you add two Vec objects. The method creates a new Vec object called "res" and returns it. ob is the object that is added to the original object, in this case "second". So ob.x is first.x - second.x and ob.y is first.y - second.y (doesn't really make sense if you ask me, but that's how it's defined in the __add__ method).
+ 1
ob is the second parameter
(lke is y in x+y )
+ 1
Ilyich Supposing that you use the '+' operator between 2 objects, effectivly you calling __add__ method on first object passing second object like parameter...In your case when python execute
res = first + second
it mean
res= first.__add__(second)
If this not answer at your question, please explain better your problem
+ 1
Imagine you have a custom class "Person" that has two member variables, name and age. If you create two instances of the class, person1 and person2, and tell python to add them (person1 + person2), python has no idea what to do (you can't just add two persons, right?).
As soon as you define a function __add__(self, other) in the class Person, the + operator will be available and you can add two Person objects. It's up to you to define what happens if you add two objects. Maybe you want to concatenate their names, maybe you want to return the sum of the ages of the single objects (maybe this is not the best example but in other cases, it is more obvious what should happen if you add two instances of a class).