Monday, 12 January 2015

What is Self?

In today's lecture, concept of "self" when defining methods was elaborated upon. Before going in to understand this, let us consider the following example:


This example defines a point and has one method. The following defines a point P then shows two ways the method can be called:


lines 3 and 4 would evaluate to the same value. The following code however returns an error

TypeError: distance_from_origin() takes exactly 1 argument (2 given)
Here, the two arguments presumably are p_dummy and p.

How is Point.distance_from_origin(X) different from p_dummy.distance_from_origin(X)?
p_dummy is an instance of class Point. Different things happen for p_dummy.method() and Point.method(). When p_dummy.method(X) is called, it searches for Point.method and calls it, passing p_dummy (which is "self") and X as variables.

Let us think about memory space. I could not find specific information about how methods are stored, but I think p_dummy does not have direct information to the method, but rather some direction (like pointer) to it. All the general information is stored in the class Point. At that point, we can think of methods as functions. what the p_dummy.distance_from_origin() does is call the function Point.distance_from_origin() with the value p_dummy.

The above is just a hypothesis about how python works based on observations. I will try to look for detailed info regarding this for a future post.

No comments:

Post a Comment