PYTHON
LECTURE 38
Today’s Agenda
• Introduction To Object Oriented
Programming-I
• Problems With Procedure Oriented Programming
• What Is Object Oriented Programming ?
• What Is A Class ?
• What Is An Object ?
• Syntax Of Creating A Class In Python
• Syntax Of Creating Object
• Types Of Data Members A Class Can Have
• The Method __init__()
• The Argument self
• Passing Parameters To __init__()
Question ???
Can you tell , what kind of programming
paradigm we have followed this point in
Python ?
The answer is : POP (Procedure Oriented
Programming)
In all the programs we wrote till now, we have designed our
program around functions i.e. blocks of statements which
manipulate data.
This is called the procedure-oriented programming.
Advantages
Advantages Of Procedure Oriented
Programming
It’s easy to implement
The ability to re-use the same code at different
places in the program without copying it.
An easier way to keep track of program flow for
small codes
Needs less memory.
Disadvantages
Disadvantages Of Procedure Oriented
Programming
Very difficult to relate with real world objects.
Data is exposed to whole program, so no security
for data.
Difficult to create new data types
Importance is given to the operation on data rather
than the data.
So , What Is The Solution ?
Solution to all the previous 4 problems is Object
Oriented Programming
Many people consider OOP to be a modern
programming paradigm, but the roots go back to
1960s.
The first programming language to use objects
was Simula 67
What Is OOP?
OOP is a programming paradigm (way of
developing programs)
In OOP, we have the flexibility to represent real-
world objects like car, animal, person, ATM etc.
in our code
It allows us to combine the data and
functionality and wrap it inside something which
is called an object
What Is An Object?
• In programming any real world entity which has
specific attributes or features can be represented
as an object.
• In simple words, an object is something that
possess some characteristics and can perform
certain functions.
What Is An Object?
• For example, car is an object and can perform
functions like start, stop, drive and brake.
• These are the functions or behaviours of a car.
• And the characteristics or attributes are color of
car, mileage, maximum speed, model , year etc.
Are We Objects ?
• Yes , we humans are objects because:
• We have attributes as name, height, age etc.
• We also can show behaviors like walking, talking,
running, eating etc
Classes
• Now to create/represent objects we first have to
write all their attributes and behaviours under a
single group .
• This group is called a class .
• Thus a class is an architecture/blueprint of the
object. It is a proper description of the attributes
and methods of the object.
Classes
• For Example:- The design of a car of same type is a
class. We can create many objects from a class. Just
like we can make many cars of the same type from a
design of car.
A Dog Class
A Student Class
Creating A Class
Defining a class is simple in Python.
We start with the class keyword to indicate that
we are creating a class, then we add the name of
the class followed by a colon
We can then add class members , which are
methods and attributes
Syntax Of Creating A Class
Syntax:
class <class_name>:
# class members
Example:
class Emp:
pass
Creating Objects
In order to use a class we have to create it’s object
which is also called instantiating a class because
objects are also called instance of the class
So, to create an instance of a class, we use the
class name, followed by parentheses and assign
it to a variable.
Syntax Of Creating Object
Syntax:
var_name=class_name( )
Example:
e=Emp()
Full Code
class Emp:
pass 1.The first line shows the class
name which is Emp.
2. The second line shows the
e=Emp() address of the object to which
the reference e is pointing
print(type(e))
3. The name __main__ is the
print(e) name of the module which
Python automatically allots to
our file
Output:
Adding
Data Members/Attributes
Once we have defined the class , our next step is to
provide it data members/variables which can be used to
hold values related to objects.
In Python , a class can have 3 types of variables:
Instance Variables: Created per instance basis
Local Variables: Created locally inside a method and destroyed
when the method execution is over
Class Variables: Created inside a class and shared by every
object of that class. Sometimes also called as static variables
What Is An Instance Variable?
Object variables or Instance Variables are
created by Python for each individual object of
the class.
In this case, each object has its own copy of the
instance variable and they are not shared or
related in any way to the field by the same name in
a different object
Creating Instance Variables
Creation of instance variables in Python is
entirely different than C++ or Java
In these languages , we declare the data members
inside the class and when we instantiate the
class , these members are allocated space .
Creating Instance Variables
In C++
For example in C++ ,we would write :
class Emp Now to use this Emp class we would say:
{
Emp obj;
int age;
char name[20]; Doing this will create an object in memory by
double salary; the name e and will contain three
…….. instance members called as
…….. age , name and salary . Also this line
will automatically call a special method
};
These are called constructor for
called initializing the object
instance
variables
in C++
Creating Instance Variables
In Java
In Java ,we would write :
class Emp Now to use this Emp class we would say:
{
Emp obj=new Emp( );
int age;
String name; Doing this will create an object in heap with
double salary; the data members as age , name and salary
…….. and the reference e will be pointing to that
…….. object. Here also the special method
called constructor will be called
}
These are automatically for initializing the object
called
instance
variables
in Java
Creating Instance Variables
In Python
But in Python we use a very special method called
__init__() , to create as well as initialize an object’s
initial attributes by giving them their default value.
Python calls this method automatically , as soon as the
object of the class gets created.
Since it is called automatically , we can say it is like a
constructor in C++ or Java.
Full Code
class Emp:
def __init__(self):
print("Object created. . .")
As you can observe ,
e=Emp()
Python has
automatically called
Output: the special method
__init__() as soon as
we have created the
object of Emp class
Another Example
class Emp:
def __init__(self):
print("Object created. . .")
e=Emp()
f=Emp()
g=Emp()
Output:
The argument self ?
You must have noticed that the code is using an
argument called self in the argument list of
__init__()
So , now 2 questions arise , which are :
What is self ?
Why it is required ?
What Is self ?
In Python , whenever we create an object , Python
calls the method __init()__
But while calling this method , Python also passes
the address of the object , for which it is calling
__init__() , as the first argument.
Thus , when we define the __init__() method we
must provide it atleast one formal argument
which will receive the object’s address .
This argument is named as self
What If We Don’t Create self ?
class Emp:
def __init__():
print("Object created. . .")
As you can observe ,
Python has generated an
e=Emp() exception , since it has
passed the object
address as argument
while calling the method
__init__() but we have not
declared any argument
to receive it
Output:
Can We Give Some Other Name
To self ?
class Emp:
def __init__(myself):
print("Object created. . .")
As you can observe ,
e=Emp() Python has allowed us to
use the name myself
instead of self , but the
convention is to always
use the word self
Output:
More About self
Python always passes address of the object to
every instance method of our class whenever we
call it, not only to the method __init__()
So, every instance method which we define in our
class has to compulsorily have atleast one
argument of type self
More About self
The argument self always points to the address
of the current object
We can think it to be like this reference or this
pointer of Java or C++ languages
Is self A Keyword ?
No , not at all
Many programmers wrongly think self to be a
keyword but it is not so.
It is just a name and can be changed to anything else
but the convention is to always use the name self
Another Important Point!
The argument self is local to the method body , so
we cannot use it outside the method
Guess The Output
class Emp:
def __init__(self):
print("Object Created...")
e=Emp()
print(self)
Output:
The Most Important Role
Of self
We can also use self to dynamically add instance
members to the current object.
To do this ,we simply have to use self followed by dot
operator followed by name of the variable along with
it’s initial value
Syntax:
class <class_name>:
def __init__(self):
self.<var_name>=value
.
.
Example
The variables
class Emp: self.age,self.nam
e and self.salary
def __init__(self): are called
instance
self.age=25 variables
Remember , we cannot
self.name="Rahul" use self outside the
class . So outside the
self.salary=30000.0 class we will have to
use the reference
variable e
e=Emp()
print("Age:",e.age,"Name:",e.name,"Salary:",e.sala
ry) Another very important
point to understand if you
are from C++ background
Output: is that in Python by
default everything in a
class is public . So we can
direclty access it outside
the class
A Very Important Point!
The instance variables called age , name and
salary are accessed in 2 ways in Python:
Inside the methods of the class , they are always accessed
using self so that Python will refer them for current object
Outside the class , we cannot access them using self because
self is only available within the class.
So outside the class we have to access them using the object
reference we have created
Guess The Output ?
class Emp:
def __init__(self): Unlike C++ or Java ,
self.age=25 in Python we can
self.name="Rahul" create instance
variables outside
the class by directly
e=Emp() using the object
e.salary=30000.0 reference
print("Age:",e.age,"Name:",e.name,"Salary:",e.salary)
Output:
A Problem With The Code
Although the code works fine , but it has one
problem .
The problem is that for every object of Emp class ,
Python will call __init__() method and thus every
object will be initialized with the same values
To overcome this problem we can make the method
__init__() parameterized
Passing Parameters
To __init__()
Since __init__() is also a method so just like other
methods we can pass arguments to it .
But we need to remember 2 things for this:
Since __init__() is called by Python at the time of object
creation so we will have to pass these arguments at the time
of creation of the object
We will have to define parameters also while defining
__init__() to receive these arguments
Finally using these parameters we can initialize
instance members to different values for different
objects
Passing Parameters
To __init__()
class Emp:
def __init__(self,age,name,salary):
self.age=age The variables age,
self.name=name name an salary are
self.salary=salary called local
variables
e=Emp(25,"Rahul",30000.0)
print("Age:",e.age,"Name:",e.name,"Salary:",e.salary)
f=Emp(31,"Varun",45000.0)
print("Age:",f.age,"Name:",f.name,"Salary:",f.salary)
Output:
An Important Point
The argument self , should always be the first argument
as Python passes the address of the current object as the
first argument
The variables age , name and salary used in the
argument list of __init__() are called parameters or
local variables.
They will only survive until the method is under
execution and after that they will be destroyed by
Python
An Important Point
Any variable declared inside the body of any
method inside the class without using self will also
be called as local variable
It is a common convention to give parameters
the same name as instance members , but it is
not at all compulsory.
Passing Parameters
To __init__()
class Emp:
def __init__(self,x,y,z):
self.age=x
self.name=y
self.salary=z
e=Emp(25,"Rahul",30000.0)
print("Age:",e.age,"Name:",e.name,"Salary:",e.salary)
f=Emp(31,"Varun",45000.0)
print("Age:",f.age,"Name:",f.name,"Salary:",f.salary)
Output:
Guess The Output ?
class Emp:
e1=Emp("amit")
def __init__(self,name):
e2=Emp("sumit",23)
self.name=name
e3=Emp("deepak",34,50000.)
def __init__(self,name,age):
print(e1.name)
self.name=name
print(e2.name,e2.age)
self.age=age print(e3.name,e3.age,e3.sal)
def __init__(self,name,age,sal):
self.name=name
self.age=age
self.sal=sal
Output:
Why Didn’t The Code Run ?
Recall , that we have already discussed that
PYTHON DOES NOT SUPPORT
METHOD/FUNCTION OVERLOADING .
So if two methods have same name then the
second copy of the method will overwrite the first
copy.
So , in our case Python remembers only one
__init__() method , which is defined last and since it
is taking 3 arguments (excluding self) so our call:
e1=Emp(“amit”)
generated the exception
Question ?
Can we do something so that the code runs
with different number of arguments passed to
Emp objects ?
Yes !
The solution is to use default arguments
Solution
class Emp:
def __init__(self,name,age=0,sal=0.0):
self.name=name
self.age=age
self.sal=sal
e1=Emp("amit")
e2=Emp("sumit",23)
e3=Emp("deepak",34,50000.)
print(e1.name)
print(e2.name,e2.age)
print(e3.name,e3.age,e3.sal)
Output: