How to Use __init__() Function in Python


In this example we will show how to use the __init__() function in Python.

Source Code

class Sum:
    # All classes have a function called __init__(), which is always executed when the class is being initiated.
    # Use the __init__() function to assign values to object properties, or other operations that are necessary to do when the object is being created.
    def __init__(self, a, b):
        self.a = a
        self.b = b

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

sum1 = Sum(2, 6)
print(sum1.a)
print(sum1.b)

Output:

2
6
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments