10) c. Creating an Instance of a Class

When you create an instance of a class it means that you’re creating a structure in Python’s working memory that will have the variables that you defined as class attributes and will have functions that you declared as class methods.

An instance of a class is nothing but a class object that has been loaded into the memory.

display function called successfully!

In the example above, the actual object creation in memory happens when we call the class Player() and assign that memory to a namespace beardy.

While instantiating a class, a method is called in the background which is built-in by default. This is called the __init__ method. This method is called the constructor of the class. Even if you don’t define the __init__ method, it will be auto-defined and called when you instantiate the class.

Another thing to note here is how the __init__ method has double-underscores around its name. Any method that has double-underscores like this is a special method which exists by default for a class, irrespective of whether or not you create it.

The values that the class attributes store in the instance are called as state of the class.

It is very likely (though not necessary) that your class will have some attributes because you would want your class object to store some values. This is where instances and the __init__ method come into play.

Declaring an __init__ method of your custom class allows you to dictate your own logic of how initial state of a new instance is setup. Usually you would initialize all of your instance variables.

As you can see, in order to create an instance variable you need to access attribute health of the instance self and assign the value. Note that the methods of this class always take self as the first argument which is the instance of the class.

You can also customize the __init__ method by adding parameters.