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.

class Dog:
    scientific_name = "canis lupus familiaris"
    
    def __init__(self, name, age, fur_color):
        self.name = name
        self.age = age
        self.fur_color = fur_color
    
    def bark(self):
        print("woof woof!!")

Now that we have defined our Dog class, how do you actually create a new dog object? We use the following notation:

# The assignment below creates a new dog object and assigns
# it to the variable "fido". This means Fido’s age is 5 and
# his fur color is black. 
>>> fido = Dog("Fido", 5, "black")

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