I have a general question on the class definition and its use..THe below code from one of the book works fine but I have a general questions.
Here we have defined a class Point and creating 2 instance Point1 & Point2. When calculating the distance for point2, how can we pass the point1 object?
Isn’t point1 the point object, whereas the other_point is reprented as a variable.
Im little confused.
Code:
import math
class Point:
def move(self, x, y):
self.x = x
self.y = y
def reset(self):
self.move(0, 0)
def calculate_distance(self, other_point):
print("Inside calculating distance")
return math.sqrt(
(self.x - other_point.x)**2 +
(self.y - other_point.y)**2)
point1 = Point()
point2 = Point()
point1.reset()
point2.move(5,0)
print(point2.calculate_distance(point1))
That’s what the
selfvariable does. So when you are inside the definition of a class, you can useselfto identify the object whose data you are trying to manipulate.For example, suppose you have a class called human (which has a member variable named
age), and every year, you want to increase the age of that human by calling theincrement_agefunction. Then, you could write the following code:So you see, by calling
self, you are referring to the object itself. In your example, this would translate toselfreferring topoint1.Now, suppose that in the
Humanclass, we want to add a function that allows two humans to fight. In this case, one human would have to fight another human (suppose that fighting another human increases your life by one and decreases the other human’s life by one). In that case, you could write the following function within theHumanclass:Now:
Thus you can see in this example that
h2is theother_humanin thefightfunction.Hope that helps