How to Create an Instance of a Class in Python 


               


How to Create an Instance of a Class in Python



Python


In this article, we show how to create an instance of a class in Python.

So, an instance of a class is a new object of a class.

So, if we have a class named Students, an instance of this class may be Student1, Student2, Student3, etc.

So once we have created a class, how do we create an instance of a class that represents an object of a class in Python?

So below, we show how this is done.

We create a class named Student and create an instance of this class, Student1.



So this is pretty much the most basic type of class and instance that you can create in Python.

We create a class named Student.

In this Student class, we use the keyword pass. What this does is allows us to specify nothing in the class, no attributes, no methods, etc. If you simply left the area completely blank, Python would throw an error. So the keyword, pass, must be used.

We then create an instance of this Student class.

We name the instance, Student1, and set it equal to the name of the class (we are creating an instance of)

In this case, since we are creating an instance of the Student class we set Student1 equal to Student()

Now if you enter Student1 into the Python console, you get the following output.



So, you can see that Student1 is an instance, or object, of the Student class.

So, all you have to do to create a new instance of a class in Python is choose a name for the object and set it equal to the class name (that you created) followed by ().

When referencing a class in Python, it should always be the class name with parenthesis ().

And this is all that is needed to create an instance of a class in Python.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...