Different faces of Python methods
Until now, we’ve been implementing methods that have performed operations on the instances (objects), and in particular the attributes of the instance, so we’ve called them instance methods.
The instance methods, as the first parameter, take the self
parameter, which is their hallmark. It’s worth emphasizing and remembering that self
allows you to refer to the instance. Of course, it follows that in order to successfully use the instance method, the instance must have previously existed.
The code in the editor demonstrates the idea presented above.
Each of the Example class objects has its own copy of the instance variable __internal
, and the get_internal()
method allows you to read the instance variable specific to the indicated instance. This is possible thanks to using self
.
The name of the parameter self
was chosen arbitrarily and you can use a different word, but you must do it consistently in your code. It follows from the convention that self literally means a reference to the instance.