Continuing my journey through OOP has brought me to the self parameter and the __init__ method.
The self parameter is required in every method of a class. In OOP, a method operates on a specific object’s data attributes. When a method executes, it must have a way of knowing which object’s data attributes it is supposed to operate on. That’s where the self parameter comes in. When a method is called, Python makes the self parameter reference the specific object that the method is supposed to operate on. When a method is called, Python automatically passes a reference to the calling object into the method’s first parameter. As a result, the self parameter will automatically reference the object on which the method is to operate.
__init__ is commonly known as the initializer method because it initializes the object’s data attributes. __init__ is automatically executed when an instance of the class is created in memory. The __init__ method is usually the first method inside a class definition.
class Fish():
def __init__(self, type):
self.type = type
trout = Fish("trout")
- An object is created in memory from the Fish class.
- The Fish class’s __init__ method is called, and the self parameter is set to the newly created object.
- After these steps take place, a Fish object will exist with its type attribute set to the argument passed to the class (in this case trout).
- the = operator assigns the Fish object that was just created to the
trout
variable. - the trout variable will reference the Fish object, and that object’s type attribute will be assigned the string “trout”