Instantiation
Instantiation is how you make a new instance of a class.
Provided below is a copy of the dog class from the last section for your convenience. We will be referring to it throughout this section.
Now that we have defined our Dog class, how do you actually create a new dog object? We use the following notation:
The parameters of the Dog() constructor above refer to the parameters of the Dog constructor. If you look at the code for the dog class, you might see a weird-looking method with underscores on both sides, __init__, which is called the constructor. These magic methods are called implicitly when you create an instance (a new object) of a class. This is instantiation.
Self
When you instantiate Dog(“Fido”, 5, “black”), the __init__ method is called by python automatically. This constructor “constructs” our new dog object, with the passed in instance variables to self.instance_attribute. Self is a new piece of syntax that essentially allows us to refer to a particular instance of a class.
The constructor assigns the name of our dog to “Fido”, the age of our dog to the integer 5 and the fur color to the string “black” like any other function does and assigns the whole object to the variable fido so we can refer to it later on in our code.
Visualization
One cool thing about OOP is that unlike normal functions where the variables are not accessible outside of the function call, we can still access these attributes after the method finishes running. If we were to visualize what our new dog Fido would look like in our python program it would look like this:
How do you actually access fido’s variables if they are just inside this “box”? We use a type of notation called dot notation.
Last updated
Was this helpful?