How To Call A Class Method In Python

In this tutorial, you’ll learn how to call a class method in Python. Python provides powerful object-oriented programming (OOP) capabilities. One of the core features of OOP is the ability to define methods within classes that can be called on instances of those classes. Let’s dive in!

Step 1: Define a Python class and method

To begin with, let’s create a simple Python class that has just one method. This method will be called display_message(), and it will print a user-provided message. Here’s the class definition:

Step 2: Create a class instance

The next step is to create an instance of the class we just defined. This will allow us to call the display_message() method.

When you create a new instance, the class constructor (__init__() method) is automatically called, but since we haven’t defined a constructor in our class, Python will use its default constructor.

Step 3: Call the class method

Now that we have an instance of the class, it’s time to call the display_message() method. You can do this by using the dot notation (.) followed by the method name and its arguments.

When you run this code, the output will be:

Hello, World!

And, that’s it! You’ve successfully called a class method in Python.

Complete example code

Here’s the complete code for the given example:

You can run the complete example above to see that it successfully calls the class method and displays the desired output.

Conclusion

In this tutorial, you’ve learned how to call a class method in Python. Class methods are a fundamental part of object-oriented programming in Python, and understanding how to call them is essential for working with Python’s powerful OOP capabilities. Keep practicing and experimenting with different classes and methods to get a better grasp of this important concept. Happy coding!