• The instantiation or calling-a-class-object operation creates an empty object. Many classes like to create objects with instances with a specific initial state. Therefore a class may define a special method named __init__(), as f">

    How to create instance Objects using __init__ in Python?



    • The instantiation or calling-a-class-object operation creates an empty object. Many classes like to create objects with instances with a specific initial state. Therefore a class may define a special method named __init__(), as follows −
    • def __init__(self) −
    •     self.data = [ ]
    • When a class defines an __init__() method, class instantiation automatically invokes the newly-created class instance which is obtained by −
    • x = MyClass()
    • The __init__() method may have arguments. In such a case, arguments given to the class instantiation operator are passed on to __init__(). For example,
    >>> class Complex:
    ...     def __init__(self, realpart, imagpart):
    ...         self.r = realpart
    ...         self.i = imagpart
    ...
    >>> x = Complex(4.0, -6.5)
    >>> x.r, x.i
    (4.0, -6.5)
    
    
    Kickstart Your Career

    Get certified by completing the course

    Get Started
    Advertisements