How to Create a Method in a Class in Python


In this example, we will learn how to create a method in a class and call it in Python.

Source Code

class Sum:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    # create a method
    def my_function(self):
        s = self.a + self.b
        print(s)

sum1 = Sum(2, 6)
sum1.my_function()

Output:

8
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments