§ Whenever
a class is instantiated __new__ and
__init__ methods are called.
§ __new__
method will be called when an object is created and __init__
method will be called to initialize the object.
§ __new__()
method in Python class is responsible for creating a new instance object of the
class. __new__() is similar to the constructor method in other OOP (Object
Oriented Programming) languages such as C++, Java and so on.
def
__new__(cls)
§ The
first parameter cls represents the class being created.
§ In
the base class object, the __new__ method is defined as a
static method which requires passing a parameter cls. cls represents the class
that is needed to be instantiated, and the compiler automatically provides this
parameter at the time of instantiation.
§ The
major difference between these two methods is that __new__
handles object creation and __init__ handles object
initialization.
§ __new__ is called
automatically when calling the class name (when instantiating)
§ whereas __init__
is called every time an instance of the class is returned by __new__
passing the returned instance to __init__ as the 'self' parameter,
§ Constructors
are executed as part of the object creation.
class A(object):
# -> don't forget the object specified
as base
def __new__(cls):
print("A.__new__ called")
return super(A,
cls).__new__(cls)
def __init__(self):
print("A.__init__ called")
#let's create an object
A()
__init__ () method in Python
§ If
we want to perform any operation at the time of object creation the suitable
place is __init__ function.
§ In a single word __init__ is a special member
method which will be called automatically whenever object is created.
§ The
name of the init should be __init__(self).
Purpose Of __init__§ The purpose of __init__ is to initialize an
object called object initialization. __init__ are mainly created for
initializing the object. Initialization is a process of assigning user defined
values at the time of allocation of memory space.
§ __init__ can take at least one argument (at least self)
def __init__(self):
§
Per object __init__ will be executed only once.
class Test:
def
__init__(self):
print(" Class Test __init__ exeuction...")
# instantiate the Car class
t1=Test()
t2=Test()
t3=Test()
Output:
Class Test __init__ execution's…
Class Test __init__ execution's…
Class Test __init__ execution's…
Example:
class Person:
def __init__(self,name,age,sex,weight,height):
self.name=name
self.age=age
self.sex=sex
self.weight=weight
self.height=height
def eating(self,msg):
print(msg)
def displayPersonInfo(self):
print("Name:
",self.name)
print("Age:
",self.age)
print("Sex:
",self.sex)
print("Weight:
",self.weight)
print("Height:
",self.height)
mark=Person("Mark",45,"Male",30,4.5)
mark.displayPersonInfo()
mark.eating("Can eat only Non-Veg Food")
print("===================================")
sachin=Person("Sachin",55,"Male",70,5.5)
sachin.displayPersonInfo()
sachin.eating("Can eat only Veg Food")
Rules or properties of a __init__
§ A __init__ () initializes the
object immediately when it is created.
§ Constructor executes only once in
the object’s life cycle.
§ It can accept some arguments.
. Types of __init__in Python
ü A __init__() is a special kind of method which is used for initializing the instance
variables during object
creation.
ü We have
two types of __init__() in Python.
1.
Default __init__()
2.
User defined __init__()
Default __init__
class Test:
def m1(self):
print('Hello')
#create
an object of class
t1=Test()
t1.m1()
ü In this
example, we do not have a __init__ but still we are able to create an
object
for the class. This is because there is a default constructor implicitly
injected
by python during program compilation, this is an empty default
constructor that
looks like this:
def __init__(self)
# no
body, does nothing.
Parameterized constructor example
ü
When we declare a
constructor in such a way that it accepts the arguments during object creation
then such type of constructors is known as Parameterized constructors.
class Test:
def __init__(self,n1,n2):
self.a=n1
self.b=n2
def display(self):
print("a= ",self.a)
print("b= ",self.b)
#create an object of class
t1=Test(10,20)
t1.display()
t2=Test(30,40)
t2.display()
No __init__ Overloading in Python
More than One Python
__init__
ü
If you give it more than
one __init__, that does not lead to overloading.
ü
If you define the more
than one same kind of __init__, then it will be considered the last
__init__ and ignore the earlier constructor.
class Test:
def __init__(self):
print("First init ")
def __init__(self):
print("Second init ")
def __init__(self):
print("Third init")
#create
an object of class
t1=Test()
Output:
Third init
Two Different Kinds of
__init__ in Python
class Test:
def __init__(self):
print("First
init")
def __init__(self,a):
print("Second
init")
self.a=a
#
creating object of the class
t1=Test()
t1=Test()
TypeError:
__init__() missing 1 required positional argument: 'a'
class Test:
def __init__(self):
print("First
init")
def __init__(self,a):
print("Second
init")
self.a=a
#
creating object of the class
t1=Test(10)
Output:
Second init
Using Default Arguments
üEven the following piece of code is simply the use of
default arguments, not overloading:
class Test:
def __init__(self,a=10,b=20):
print("init calling...")
self.a=a
self.b=b
print("a= ",self.a,"b=",self.b)
#
creating object of the class
t1=Test()
t2=Test(40)
t3=Test(50,60)
Output:
init calling...
a=
10 b= 20
init calling...
a=
40 b= 20
init calling...
a=
50 b= 60
Difference
between Method and Constructor
|
Method
|
Constructor
|
1
|
Method
can be any user defined name
|
Constructor
name should be always __init__
|
2
|
Method
should have return type
|
It
should not have any return type (even void)
|
3
|
Method
should be called explicitly either with object reference or class reference
|
It
will be called automatically whenever object is created
|
4
|
Inside
Method we can write business logic
|
Inside
Constructor we have to declare and initialize instance variables
|
Post a Comment