0% found this document useful (0 votes)
3 views

Oop in python

The document provides an overview of Object-Oriented Programming (OOP) in Python, detailing key concepts such as classes, objects, inheritance, encapsulation, and polymorphism. It emphasizes the importance of OOP in modeling real-world scenarios and offers examples of class syntax and method invocation. Additionally, it discusses the use of Class-Based Views in Django for web application development, highlighting the advantages of this approach over function-based views.

Uploaded by

dhruvmehta224
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Oop in python

The document provides an overview of Object-Oriented Programming (OOP) in Python, detailing key concepts such as classes, objects, inheritance, encapsulation, and polymorphism. It emphasizes the importance of OOP in modeling real-world scenarios and offers examples of class syntax and method invocation. Additionally, it discusses the use of Class-Based Views in Django for web application development, highlighting the advantages of this approach over function-based views.

Uploaded by

dhruvmehta224
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

CyberSquare

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

that you want to model in your program. An objectc can be


account, etc.

Python is ahigh level programming language that supports both object


programming,impoermtpalocyees,te
to data ratherthan just writing instructions to complete atask. An
object is athing
anything, Ex: it,
oriented
a

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

Moduie Figure 2-1


WWw.CV
Software WorlobjeCts in
the Create the world of
Objectsin real World, we canidentity. computer
lust like in the nameas
will have
a attributes.
Which to define its
(variables)
of'customer'are name, phone number.
Properties
Attributes update/process properties(data).
address, etc.
Functions(methods) to

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

this base design as"Class"


functionalifties thathe.
we call
programming terms,
In
number of objects of that type.
class, we can create any
loaded to the primary memory of
Objects are
the
a
Simply by having structure of the class is Compute
created when the objects.
design of
Class : is the base
the instance of a class.
Object : is
theb3..
created. Class is stored as a.py fle in
memory is allocated when a class is memnory is used while creating a clasc
No
space in main(primary)
the comnputer. No
object is created. Structure of the class is loadedton
an
Memory is allocated only when
object.
memory to create an

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 =

def init (self, name, salary) :


self. name = name
self.salary = salary
Employee.emp count +* 1

def display count (self) :


print "Total Employee %d" % Employee.emp count

def display employee (self):


print "Name self.name, Salary: self.salary

In the above example of class "Employee", variables "name" and


"salary" are instance variables and,
"emp_count" is a class variable(static variable). Each object will have a copy
whereas static variable will have only one instance and will be shared by all of instance variable,
instances of the class.
You can create instances of the class as follows:

empl = Employee (" John", 15000)


emp2 = Employee ("George'" , 20000)

After executing the code shown above, an object will be


representation is given in the figure below. created in the memory. A pictorial

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

Abstraction and Encapsulation


Abstraction
It is one of the fundamental concepts of 00P. Abstraction is a process where you show only teas
data and "hide" unnecessary details of an object from the user. For example, when you bogin tuu
tacebook account you go to facebook.com, key-in your username and password, cick on te g
button, and the home page is displayed. Youdon't have any idea about how the autienu
done. The process of authentication is abstracted from the user.

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

Wrappingup of data and Hides internal functionalities


methods as a single unit. from user.
Solves the problem at Solves the problem at design
implementation level. level.

Inner layout in terms of Outer layout used in terms of


implementation. design.
Ex: Inner implementation of mobile
phone Ex: Outer look of mobile phone

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)

a1f salary Slary


def get Salary(se1f):
Feturn s1f, salary
(etles llow us to validate a tal,
Ietonly or writeonily by orrttirig the tter ardthe We Can
getter asO maig.
respectively.
Inheritance
Inheitane is a mechanIsn in which one
class cquires the
inheitnce, we can reuse the fieids and methocs of the property of
reusability of code and is an important conceot of 00P. existing dass. Hence, inherHte
Create a class by deriving from an éxisting cdass
Allthe methods and properties are
accessible from the child dass
Childclass can override properties and methods.
Python supports multiple inheritance.
It helps to avoid duplication of code.

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

def name (self): 4 self.last name)


name
print(self. first
details (self) :
def print
an employee,
print ("8s %s is self. last name, ))
self. first name,

(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

Class based views


The application
Wehave learned to develop web applications using the Python django framework.
powerful featuress of
we developed uses a function based approach. Class Based Views are very
be
django, which heavily-utilises Python's object orientation and multiple inheritance in order to
extensible.

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

Install Virtual Environment -Ubuntu/ Mac


and open terminal.
" Search "terminal" on the search bar of ubuntu
the terminal.
To installvirtualeny, type the command below on
sudo pip install virtualenv.
Create a virtual environment.
virtualenv myenv
(myenv is the name of the virtual environment)
35
2 Module www.cybersquare.org
Cyber Square executing the

After installation you have to


activate your virtual
environment by
fol owing
COmmand:
SOurce <environment name>\bin\activate

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/!

Create index.html inside the templates folder.

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>

Add code to views.py


From django.views.generic import View, TemplateView
Erom django.http import HttpResponse

class FirstCbv (View):


def get (self, request) :
return HttpResponse (Nelcone to cyberequarc)

class Index (TemplateView)


template name = 'index. html

def get context data (self, **kwaros)


context super ().get context data (**kwargs)
context['name'] = Cybersquare
return context

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

Elass SanpleVier (Vie):


def gett (self, request) :
# Code block for GET request

def post (self, request):


# Code block for POST request

are required
ne seeanc dsolav cata from caabase multiole lines ofcoce

ef ite list (request) :


template nare = 'iten list.htul
itens = Ite.objects.all ()
data = }
data['object list'] = items
return render (request, template name, data)
39
2 www.C0ersquare org
BV witlhiust ty
ahevedinCh
same can be
The (ListView)!
blass I temList
model = Item
'item list.htm1
template name

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

You might also like