Featured

    Featured Posts

Python OOPS Tutorial 3:Constructor in Python




§  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






Python OOP Tutorial 1: Difference between Procedure Oriented and object oriented programming language?



OOP's Concept in Python
 §  Object-Oriented Programming is a methodology or paradigm to design a program using classes and objects. 
 Ã¼ Object
 Ã¼ Class 
 Ã¼ Inheritance
 Ã¼ Polymorphism
 Ã¼ Abstraction
 Ã¼ Encapsulation
Object
§  Objects are key to understanding object-oriented technology. Look around right now 
and you will find many examples of real-world objects: your dog, your desk, your television set, your bicycle etc.

§  Object is a real-world entity.
Class
§  class is a logical model for creating an object.
§  class is a blue point of an object.
Encapsulation
 §  Encapsulation: In normal terms, Encapsulation is defined as wrapping up of data and information under a single unit. In Object-Oriented Programming, Encapsulation is defined as binding together the data and the functions that manipulate them.

 §  Combining of state and behavior in a single container is known as encapsulation. In Python language encapsulation can be achieve using class keyword, state represents declaration of variables on attributes and behavior represents operations in terms of method.
Abstraction: - 
§  Hiding the internal implementation and highlighting the set of services that process is called abstraction. 
§  Another way, it shows only important things to the user and hides the internal details for example sending sms, you just type the text and send the message. You don’t know the internal processing about the message delivery.

§  Abstraction lets you focus on what the object does instead of how it does it.
Ex:- 
a.      Bank ATM Screens (Hiding thee internal implementation and highlighting set of services like withdraw, money transfer, mobile registration). 
b.     Mobile phones (The mobile persons are hiding the internal circuit implementation and highlighting touch screen). 
c.      Syllabus copy (the institutions persons just highlighting the set of contents that persons provided the persons are not highlighting the whole content). 

Polymorphism

 §  The process of representing one Form in multiple forms is known as Polymorphism.

 §  Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means many forms.



Real Time Polymorphism Example
Inheritance


 §  The process of obtaining the data members and methods from one class to another  
       class is known as inheritance. It is one of the fundamental features of object-oriented 
       programming.

What are the 4 Pillars of OOPs ?

Abstraction, Inheritance, Encapsulation and Polymorphism are the four pillars of OOPs.

 
v Difference Between Encapsulation and Abstraction in Java

   Abstraction means hiding the complex details and showing the only essential details which is required to the end user whereas encapsulation means bind your data and code together as a single unit.
   
Difference between Procedure Oriented and object oriented programming language?

Answer: -



Procedure Oriented
object oriented
Divided into
In POP program is divided
into small parts called
functions.
In OOP program is divided into parts called objects.
Importance
In POP importance is not given to data but to function as well as sequence of actions to be done.
In OOP importance is given to the data rather than procedures or functions because it works as a real world.

Approach
POP follows TOP Down approach
OOP follows Bottom UP approach
Access Specifier
POP does not have any access specifier.
OOP has access specifier named public, private, protected etc.
Data Moving
In POP data can move freely from function to function in the system.
In OOP object can move and communicate with each other through member functions.
Expansion
To add new data and function in POP is not so easy
OOP provides an easy way to add new data and function.

www.CodeNirvana.in

Powered by Blogger.

About

Site Links

Popular Posts

Translate

Total Pageviews