Python provides the __init__()
method inside the class definitions in order to construct newly created objects or instances. The __init__() method accepts multiple parameters that are provided during the object initialization and used inside the __init__() method body.
__init__() with Parameters
The __init__() method is used to accept parameters and these parameters are generally used to construct the object. Object construction is generally setting provided parameter values into the object variables. In the following example, we create an instance of the Person class using the __init__() method.
class Person:
name=""
age=-1
def __init__(self,name,age):
self.name=name
self.age=age
ismail = Person("İsmail Baydan",38)
Multiple __init__() Methods
Python class can be defined in a complex way with multiple variables. This class can be used in different ways with different initialization methods. We can use multiple __init__() methods in a single class. These methods should accept different counts of parameters.
class Person:
name=""
age=-1
def __init__(self,name,age):
self.name=name
self.age=age
def __init__(self,name):
self.name=name
self.age=age
ismail = Person("İsmail Baydan",38)
ismail = Person("İsmail Baydan")
__init__() with Inheritance
Like most object-oriented programming languages the Python class has the inheritance feature. If a class is derived from another class there will be multiple __init__() methods. We can call the base class __init__() method from derived class __init__() method.
class Person:
name=""
age=-1
def __init__(self,name,age):
self.name=name
self.age=age
class Student(Person):
grade=-1
def __init__(self,name,age,grade):
Person.__init__(self,name,age)
self.grade=grade
ismail = Person("İsmail Baydan",38)
student_ismail = Student("İsmail Baydan",38,12)