Intro to OOP (Part 2)

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")

  1. An object is created in memory from the Fish class.
  2. The Fish class’s __init__ method is called, and the self parameter is set to the newly created object.
  3. 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).
  4. the = operator assigns the Fish object that was just created to the trout variable.
  5. the trout variable will reference the Fish object, and that object’s type attribute will be assigned the string “trout”

About grug_life

Finance Professional, Adjunct Professor of Python, Aspiring Data Nerd
This entry was posted in Uncategorized and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s