How To Call An Instance Of A Class In Python

In this tutorial, we will learn how to call an instance of a class in Python. It is an essential concept in object-oriented programming, useful for creating reusable codes and better-organized programs. Keep reading to understand the process of creating a class, instantiating it, and using its methods and properties.

Step 1: Define the Class

To start, first, we need to create a class. A class is a blueprint for creating objects with common attributes and methods. Below is an example of a basic Python class named Person:

This class has an initialization method __init__ that accepts two arguments, name and age. It also has a method called say_hello that outputs a message when called.

Step 2: Instantiate the Class

Now that we have a class, we need to create an instance of it. To do this, we should call the class by providing the required arguments for its constructor. Here’s how we create an instance of the Person class:

In this case, we have created an instance of the Person class named person1. The name attribute will be “John” and the age attribute will be 30.

Step 3: Call a Method from the Instance

With our person1 instance, we can now call its method say_hello. To do so, we simply write the instance’s name, followed by a dot (.) and the method’s name with parentheses:

This line of code will call the say_hello method from the person1 instance and output its message.

Step 4: Run the Code

Now, let’s put everything together and run the code. Here’s our complete program:

Output:

Full Code

Conclusion

In this tutorial, we have learned how to call an instance of a class in Python. By defining a class, instantiating it and calling its methods, we can create versatile and flexible codes for various applications. Keep practicing to master these concepts and enhance your Python programming skills.