How to create instance Objects using __init__ in Python?

PythonServer Side ProgrammingProgramming

  • 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) −
  • = [ ]
  • 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)

Published on 12-Jan-2018 11:27:22