How To Call Method From Another Class Python

In this tutorial, we will learn how to call a method from another class in Python. This is a crucial concept in object-oriented programming and helps in making code more modular, reusable, and maintainable.

Step 1: Define Classes and Methods

First, let’s define two classes with methods that we would like to call across the classes. One of the classes will have a method that the other class needs to access. Consider the following example:

In this example, we want to call method_one from ClassA inside ClassB.

Step 2: Call a Method from Another Class

To call a method from another class, you have a few options. These options include creating an object of the class you are calling the method from or using inheritance.

Create an Object of the Class

You can create an object of the class containing the method you want to call and then call the method on that object. This is the simplest approach.

Here is an example:

In this example, we created an object class_a_object of ClassA inside the method_two of ClassB. Then, we called the method_one using that object.

Using Inheritance

Another way to call a method from another class is by using inheritance. Inherit the class containing the method you want to call in the class where you want to call the method.

Here is an example:

In this example, we made ClassB inherit from ClassA, and then called the method_one using the self keyword.

Full Code

When you run the code, the output will be:

This is method_two from ClassB
This is method_one from ClassA

Conclusion

In this tutorial, we learned how to call a method from another class in Python. We discussed two ways to achieve this: by creating an object of the class containing the method, and by using inheritance. Understanding these techniques is essential for working with multiple classes and methods in large Python projects.