Oop in python
Oop in python
OOP in Python
Learning outcomes
fthis module, students will|be able to:
Bythe end oft object.
1. Understand class and
using OOP(Object Oriented F
2. Write Python codes
3. Develope django
applications using Class
Based Views. Programming).
Introduction
approaches followedI by
There are two types of programming programming languages:
Procedural programming(function based): A
1.
instructions. Procedural programming makes use of
program
is a series of
program modular. This programming paradigm focuses on logic
program is used to combine both of them together.
procedures/subroutines maie
more than forda
2 Object Oriented Programming: In object oriented
programming with modules and functions. So a programmer can select the most and procedura!
programming paradigm as per the requirement for each part of the program. suitable
Before getting started with object oriented programming you should have an idea about whs.
class and an object are, and the difference between them.
When yougo to a retail shop, bank, hospital, etc. you can see computers over there. What are the
used for?
They are used for automating the business processes over there. Automation requires softwarer
addition to the hardware we see there. Software is built by using programs. Function of the sofhwet
is to keep track of all the activities going on there. So we need to simulate real life situations inte
software.
Consider a bank without computers. Banks can work without computers as banks have exstel '
fore the invention of computers. What are the activities going on in a
bank?
Customers comes to the bank to deposit or withdraw money, for taking loans, etc. You Can se
the real world is an interaction between obiects. What are the
obiects you can identity ove e
Customer, bank staff, ledger where all the banking transactions are recorded, money, etc. arethe
objects.
26 Moau
www.cybersquare.org
Real world objects will have properties(attributes)
and Cyber Square
what are the properties and actionsa
customer has?. Letactions.
list Consider the
Properties:
us Some them.object"customer,
of
Name Address, Phone no., date of
birth, blood group, height,
Actions: weight, etc.
Cuctomers can create an account inthe
bank, deposit, and
If we areable to map the withdraw money from the
development of thee softwarecustomer
in the software as a account.
be relevant to
every business. becomes very easy. All the collection properties and
of
ers are not relevant to Here you can see that the properties
height,
and actions of an
object actions,
In object
banking, where as it is essential data in a weight, and blood group of may not
oriented hospital. custom
objects. programming, real world objects are
simulated in the software using classes and
Class
A
class is a
the plan. blueprint for creating objects.
Likewise, class is a blueprint to Supposeanwe need to build a house, the first
of an object.
Properties are create object. Class step is to draw
represented by
Structure of the customer class can be variables, and action by defines the properties and actions
class Customer:
as follows: methods(functions) in the class.
name
phone no
address
date of birth
deposit money( ):
#code for
withdraw moneydeposit
( ): here
#code for
wìthdrawal here
How are objects
All the created?
objects in the real
design. world are created out of a basic
prototype, a basic blueprint, or abase
OOP Concept
Object-oriented programming(OOP)is a style of programming that focuses on uaing
applications.
processes, or things in the real world
and build concepts,
design
object is a model of the that are mez,
toAnyourapplication. defines the properties and
We need to
should have.
create a base design which
Class in Python
Syntax of a class in python is as below:
class ClasSName:
Optional class documentation string
class suite
Example:
Cyber Square
class Employee:
Common base class for all employees
0
emp count =
MEMORY
empcount
emp1
IClass : Employee name: John
Class variable: Salary: 15000
emp_count
Member variables display_count( )
name
salary
display employee( )
Member functions: emp2
display_count( ) name: George
display_employee( ) salary: 20000
display_count( )
display_employee( )
Figure 2-2
Module
Cober Square
Calling a method
method insidee an
You can invokeícal) a object using adot
emp1.display_employee ()
Output will be:
operator, as below
Name : George Salary:
15000
init_
init "isareserved method in python. It is known as a
This method is automaticaly invVoked when an object of
Constructor is to initialize the properties(attributes) of the construclctassor Crobjeateed.ct
the class. is
in
Th
empl = Ermployee ("George", 15000)
When the above code is executed, constructor of the
ing the code inside the constructor assigns value to theclass gets
George and 15000 respectively. instance avariutomaablteiscal y
def init (self,name, salary):
self.name = name
self.salary = salary
Employee.emp count t= 1
Pillars of 0OP
Abstraction
Encapsulation
Inheritance
Polymorphism
Encapsulation in
onthedata
Encapsulation is a process of wrapping data(properties) and methods that operate wag
a single unit. It as a protective definedinsidethe
stops random access of code
wrapper that
30 www.cybersquare.org
Cyber Square
Abstraction Vs Encapsulation
Encapsulation Abstraction
Access specifiers
Access modifiers are used to implement the concept of Data Hiding in Object Oriented
Programming. There are two types of access specifiers in Python.
Public
In Python, all the methods and properties are public by default. Public property and methods in a
class can be accessed from outside using object and dot operator.
Private
Private methods or properties cannot be accessed from outside using dot operator. To make an enti
ty private, prefix the
name with double underscore(_).
Consider the class Employee shown below:
class Employee:
'Common base class for all employees
emp count = 0
def init (self, name, salary) :
self.name = name
self, salary = salary
Employee.emp count t= 1
def display employee (self):
print "Name : self. name Salary: ", self. salary
2 Module
www.cvbersquare.org 3
HalAFYslary(1 +
44the
50/190)
32 wwcoeSOuare.org
Syntax Cyber Square
Class Derivedd class (Base
,
class name [,Base class namel]
Base class
ClassOptional
suite documentation string
name2],..]):
class PerSon:
def
init
(self, fname,
self.first
self.last
name = fnamelname) :
name = lname
def name (self) :
return
self.first name self.last name
+
class
def Employee
init (Person)
:
Person. (self,
init fname,
(self,
lname
fname, staffnum)
lname)
self.staff number = staffnum
def get
employee (self)() :
return self.name + ",
self.staff number
personl =
emp1= Employee
print
Person("George",
"
Joseph")
("Tom", "Francis"
"1007")
(personl.nameemployee ())
print (empl.get
In the
() )
aboveexample,
name(). But we can haveEmployee
class Person, which these
class does not have
has properties and methodsattributes first_name, last name and
properties first_name, available in Employee class as it method
last_name and name(). inherits the
Polymorphism
Polymorphism is
the ability
have different behaviors. of an object to
take many forms.
In the
example given, Manager is a Methods bearing the same name, will
print_details().
the Manager
If we create an
objectsubclass
of
of
Employee. Both the classes have a
class is invoked but if we class"Manager"
invoked. and call method named
If we
call the
method print_details(0, the
name(), the method inside the method inside
parent class in
create an object of class
invoked. "Employee" and call print_details( ), the
method inside Employee is
2 Module
www.cybersquare.org 33
Cyber Square
class Employee: lname):
init (self, fname ,
def
name = fname
self.first
self.last name =lname
(Employee) :
class Manager fname, lname,
dept) :
def init (self,
(fname, lname)
Employee. init
self.department = dept
(self) :
def print details %s
the manager of
print ("&s %s is name,
department", &(self. first
self.last name,
self.department) )
"Francis")
e= Employee("Raymond",
Manager ("Ruby", "Mathew", "Production")
m =
# Raymond Francis
e.name ()
# Ruby Mathew
m.name ()
e.print details () # Raymond Francis is an emp loyee
m.print details() # Ruby MathewN is the manager of
# Production department
34
Cyber Square
Class-based views provide an alternative way to implement views as Python objects, instead of
functions.They do not replace function-based views, but have certain differences and advantages,
compareddtofunction--based views:
when Organization offcode related to specific HTTP methods (GET, POST, etc.) carn be
addressed by separate methods instead of conditional l branching.
orientedItechniques such as mixins (multiple inheritance) can be used to
" Object components.
factor code into reusable
Django recap
Environment - Windows
InstallVirtual
search bar of windows and opena command prompt.
Search "cnmd" on the
virtual environment in Windows, execute the following commands in the command
Toinstall
prompt:
pip install virtualenv
pip install virtualenvwrapper-win
You have to browse to the directorv using
Then create a directory for virtual environment.
command line instructions.
avirtual environment.
Execute the following command tocreate
virtualenv env
environment. You can have your own name)
(env is the name of the virtual
virtual environment by executing the following
After installation, you have to activate your
command:
<environment name>\Scripts\activate
using the command.
You can deactivate the environnment
deactivate
deactivate command.
virtual environment. use the
To deactivate
an applicationdirectory.
Let us createapplication) in the current
Create aproject(web startproject cbv
dj ango-admin
django
Create an application in directory as manage.py and
execute the com
make sure you're in the same
To create an app1,
mand:
startapp appl
python manage.py
settings.py.
of the app, in INSTALLEDAPPS section of
Add name
named"templates" inside the app1folder. TEMPLATES section of
Created a folder in the DIRS list in
Add path of the folder
Configure the template directory.
settings.py.
select any name
your application to store HTML pages. You can
You have to create a folder inside configuration in settings.py is
"templates,
the name of the folder is
of your choice for this folder. If
optional.
TEMPLATES = [
BACKEND':
'django. template.backends. django.DjangoTemplates',
DIRS!: [
BASE DIR + appl/templates/!
36 www.cybersquare.org Module
Index.htnl
Cyber Square
DOCTYPE html>
khtml lange"ens
Khead>
Ctitle>Class based views</title>
k/head>
body bgcolor="#FF9955"
hl aliqn=" center">Welcome to ((name
</h1>
k/body>
k/html>
Edit urls.py
Urls.py of project
Erom django.contríb import admin
Erom django.urls import path, include
urlpatterns = [
path ('admin/, admin.site. urls)
path ( app1/, include('app1. urls ') ),
2 Mode www.cybersquare.ore
37
rOn jaerls ort th
r yort ieNs
rlpatterns
path rieNs, Firstcv as
th`idex ieNs. TndeR
riew(0),
as
view)),
Run the project
(etlwing an ton the rot
python manaçe py runserver
The outtwl be
Nto 127.0018000 appt
http://127.0.0.1:8000/app1/index/ Fgue
127.0.0.18000 arpinder
Welcome to Cybersquare
38
Cyber SAuare
Cass baseddviews vs
functionn based views
ain -
Sale (regest):
* eT
if reDest.Methoc
# Code block for Treguest
* POST"
if reguest.ethod
reguest
# Code block for POSI
are required
ne seeanc dsolav cata from caabase multiole lines ofcoce
Summary:
programmingapproach
approach followed
are two types of
There
Procedural programming. and object orientedi prograrnming
(0OP) is a style.of
Object-oriented
using objects to
programming
design
Python is a high level
and build
programming
applications.
prograrnmirg tra
language that supports both
m
andproceduralprogramming
blueprint for creating objects.
class is a
A Python clace
init "is the name of theconstructor ina
fundamental conceptsin OOP are encapsulation, abstracticr
Thefour
and polymorphism.
Access modifiers are used toimplement the concept of Data Hiidingir e
Programming. Python hastwo. access specifiers, public
Oriented
Based Views are very powerfulfeatures of django, which andpri:
heaviy-ise
Class object orientation and multiple inheritance in order ito be extrsbe
Python's