Calling one method within another method within a class in python

class Add:
    def __init__(self, x, y):
        self.num_1 = x
        self.num_2 = y
        self.sum = 0
        
    def add(self):
        self.sum = self.num_1 + self.num_2
        return self.sum
    
    def add_another_method(self):
        #calling add method within this method within class.
        <span class="has-inline-color has-vivid-cyan-blue-color">sum_of_two_numbers = self.add()</span>
        return sum_of_two_numbers
    
add_object = Add(10,20)
<span class="has-inline-color has-vivid-cyan-blue-color">print(add_object.add_another_method())</span>
output:
30

Here in the above example, you can see “add()” is getting called within “add_another_method()” by using a variable self followed by. (dot) followed by method name (self.add()) . To call other methods within another method within a class, you have to use the “self” variable along with the method which you want to call.

Contributed by – Devanshu Kumar

Contribute article on – contribute.articles@tech-bloggers.in

Leave a Comment

Your email address will not be published. Required fields are marked *