Answers ( 2 )

  1. Object oriented languages have a concept of constructor.
    Every class has an constructor where it initialises the variables defined in it.
    Like methods, a constructor also contains collection of statements
    (i.e. instructions) that are executed at time of Object creation.

    The __init__() methods acts as a constructor in python.
    This method is called when an object is created from a class and it allows the class
    to initialize the attributes of the class.

    The word ‘self’ is used to represent the instance of a class. By using the “self” keyword
    we access the attributes and methods of the class in python.

    code Example :

    class Person:

    # init method or constructor
    def __init__(self, name):
    self.name = name

    # Sample Method
    def say_hi(self):
    print(‘Hello, my name is’, self.name)

    p = Person(‘Swapnil’)
    p.say_hi()

    Output:
    Hello, my name is Swapnil

  2. __init__ method is a constructor. This is called when an object is created from the class and it allows the class to initialize the attributes of a class. When we instantiate an object, most of the time we specify the data that we want to store inside that object. We define what is done with any arguments provided at instantiation using the init method.

    class MyClass():
    def __init__(self, string):
    self.my_attribute = string

    mc = MyClass(“Hello!”)

    When we instantiate our new object, Python calls the init method, passing in the object. We have now stored “Hello” in the attribute my_attribute inside our object which can be accessed by: print(mc.my_attribute)

Leave an answer

Browse
Browse