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:
1 2 3 4 5 6 7 |
class ClassA: def method_one(self): print("This is method_one from ClassA") class ClassB: def method_two(self): print("This is method_two from ClassB") |
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:
1 2 3 4 5 6 7 8 9 |
class ClassB: def method_two(self): print("This is method_two from ClassB") # Create an object of ClassA class_a_object = ClassA() # Call method_one from ClassA using the object class_a_object.method_one() |
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:
1 2 3 4 5 6 |
class ClassB(ClassA): # ClassB inherits from ClassA def method_two(self): print("This is method_two from ClassB") # Call method_one from ClassA (since ClassB now inherits from ClassA) self.method_one() |
In this example, we made ClassB
inherit from ClassA
, and then called the method_one
using the self
keyword.
Full Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
class ClassA: def method_one(self): print("This is method_one from ClassA") class ClassB(ClassA): def method_two(self): print("This is method_two from ClassB") self.method_one() # Create an object of ClassB class_b_object = ClassB() # Call method_two from ClassB class_b_object.method_two() |
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.