0% found this document useful (0 votes)
13 views15 pages

9&10

Uploaded by

samalashiva81
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views15 pages

9&10

Uploaded by

samalashiva81
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 15

oops:-

------:- object oriented programming specification:-


----------------------------------------------------:-
The oops principles are,
class
object
encapsulation
abstraction
Inheritance
polymorphisam

class:-
-------:-
It is a virtual and it is a blue print of an object.
object:-
--------:-
It is a physical and it is an instance of the class.
encapsulation:-
--------------:-
The process of combining or binding data and coding part.
abstraction:-
-------------:-
The process of hiding unneccessary implementations and the process of showing
neccessary implementations.
The main advantage of 'encapsulation' and 'abstraction' is 'security.
encapsulation+abstraction=security
Inheritance:-
------------:-
Inheritance is a relation between entity classes, where inharitance relation will
bring variables and methods from one class(super class/parent class/base class) to
another class(sub class/child class/derived class).
The main advantage of inharitance is 'code reusability'.
polymorphisam:-
---------------:-
poly means many and morphisam means forms.
If one thing is existed in more than one form.
The main advantage is 'flexibity' in application development.

classes in python:-
-------------------:-
The main intention of classes is to represent all real world entities in python
programming.
ex:-
----:-
student, account, customer, employee..

syntax:-
--------:-
class classname:
----docstring----
----constructor---
-----variables----
-----methods-----
procedure to use classes in python applications:-
-------------------------------------------------:-
* declare a class by using 'class' keyword.
* declare variables and methods inside the class.
* create object for the class.
* access class members.
ex:-
----:-
class Employee:
eno=111
ename='AAA'
esal=1000
eaddr='hyd'

def get_Employee_Details(self):
print('Employee details')
print('----------------')
print('Employee number is:',self.eno)
print('Employee name is:',self.ename)
print('Employee salary is:',self.esal)
print('Employee eaddr is:',self.eaddr)

emp=Employee()
emp.get_Employee_Details()

o/p:-
----:-

C:\Users\f>E:\PythonPgms\pgm\first.py
Employee details
----------------
Employee number is: 111
Employee name is: AAA
Employee salary is: 1000
Employee eaddr is: hyd

'self' variable in python:-


---------------------------:-
'self' is a default variable or default parameter in all python constructors and
python metthods, it can be used to represent current class object.

ex:-
----:-
class Student:
st_id=111
st_name='AAA'
st_addr='hyd'
st_marks=95
# declaring method
def get_student_details(self):
print('st_id is:',self.st_id)
print('st_name is:',self.st_name)
print('st_addr is:',self.st_addr)
print('st_marks is:',self.st_marks)
# object creation
Student().get_student_details()

o/p:-
----:-

C:\Users\f>E:\PythonPgms\pgm\first.py
st_id is: 111
st_name is: AAA
st_addr is: hyd
st_marks is: 95

docstring:-
---------:-
* docstring, is a string data in every python class it will provide some
description about the present class.
* docstring, is optional in python classes, we are able to write python classes
without docstring but if we want to write docstring in python class then we must
provide that docstring as first statement in python class.
* To access 'docstring' from class we have to use a predefined variable like
'__doc__' by using classname

ex:-
----:-
class Account:
"This is Account class"
print(Account.__doc__)

o/p:-
----:-
C:\Users\f>E:\PythonPgms\pgm\first.py
This is Account class

ex:-
----:-
class Biggest:
'This program is belongs to max three numbers'
a=int(input("enter an a value:"))
b=int(input("enter an b value:"))
c=int(input("enter an c value:"))
print('Given values are:',a," ",b," ",c)
if a>b and a>c:
print('a is big')
elif b>c and b>a:
print('b is big')
elif c>a and c>b:
print('c is big')
else:
print('All are equal...')
#object creation
b=Biggest()
print(b.__doc__)

o/p:-
----:-

C:\Users\f>E:\PythonPgms\pgm\first.py
enter an a value:10
enter an b value:20
enter an c value:5
Given values are: 10 20 5
b is big
This program is belongs to max three numbers

Constructors in python:-
------------------------:-
* Constructors are used to create objects.
* Constructors are recognized and executed at the time of object creation. not
before create objects and not after create objects.
syntax:-
------:-
def __init__(self,[parameter_list])
-----instructions---------
The constructors are two types 1) default constructors
2) userdefined constructors
default constructors:-
--------------------:-
In python applications, PVM will provide default constructor.

ex:-
---:-
class Account:
print('This program belongs to default constructor...')
acc_no=111
acc_name='AAA'
acc_type='savings'
def get_account_details(self):
print('Account number is:',self.acc_no)
print('Account name is:',self.acc_name)
print('Account type is:',self.acc_type)
acc=Account()
acc.get_account_details()

o/p:-
----:-

C:\Users\f>E:\PythonPgms\pgm\first.py
This program belongs to default constructor...
Account number is: 111
Account name is: AAA
Account type is: savings

ex:-
-----:-
class Employee:
emp_no=111
emp_name='james'
emp_job='Manager'
def get_employee_details(self):
print('Employee details are')
print('*********************')
print('Empno is:',self.emp_no)
print('Emp name is:',self.emp_name)
print('Emp job is:',self.emp_job)
#object creation
Employee().get_employee_details()

o/p:-
----:-

C:\Users\f>E:\PythonPgms\pgm\first.py
Employee details are
*********************
Empno is: 111
Emp name is: james
Emp job is: Manager
userdefined constructors:-
-------------------------:-
* userdefined constructors are defined by developers as per the application
requirement.
* In every constructor 'self' parameter is default parameter.
* If we want to provide parameters explicitly to the constructors, we can provide
paramaters after self parameter.

syntax:-
-------:-
def __init__(self,[parameters...])
----instructions------------

ex:-
----:-
class Student:
def __init__(self):
self.st_id=111
self.st_name='Raju'
self.st_dob='10/10/20010'
def get_student_details(self):
print('Student id:',self.st_id)
print('Student name:',self.st_name)
print('Student dob:',self.st_dob)
Student().get_student_details()

o/p:-
-----:-
C:\Users\f>E:\PythonPgms\pgm\first.py
Student id: 111
Student name: Raju
Student dob: 10/10/20010

Variables in Python Classes:


----------------------------
In Python, the main intention of variables is to store entities data.

There are three types of variables in Python.


1. Instance Variables
2. Static Variables
3. Local variables

1. Instance Variables:
-----------------------
If any variable values is changed from one instance to another instance of an
object then that variable is called as Instance variable.
In Python applications, we are able to declare instance variables in the following
locations.
1. Inside Constuctor by using 'self' variable.
2. Inside Instance Method by using self.
3. In Outside of the class by using Object reference variables.

EX:
---
class Employee:
def __init__(self):
self.eno = 111
self.ename = "AAA"

def setEmpDetails(self):
self.equal = "BTech"
self.esal = 50000

emp = Employee()
print(emp.__dict__)
emp.setEmpDetails()
print(emp.__dict__)
emp.email = "[email protected]"
emp.emobile = "91-9988776655"
print(emp.__dict__)
Op:
---
{'eno': 111, 'ename': 'AAA'}
{'eno': 111, 'ename': 'AAA', 'equal': 'BTech', 'esal': 50000}
{'eno': 111, 'ename': 'AAA', 'equal': 'BTech', 'esal': 50000, 'email':
'[email protected]', 'emobile': '91-9988776655'}

To access instance variables data we will use the following locations.


1. Inside constructors by using self variable.
2. Inside Instance method by using 'self' variable.
3. In Out side of the class by using object reference variable.
EX:
---
class Employee:
def __init__(self):
self.eno = 111
self.ename = "AAA"
print("Inside Constructor")
print("eno value :",self.eno)
print("ename value :",self.ename)
def getEmpDetails(self):
print("Inside Instance Method")
print("eno Value :",self.eno)
print("ename Value :",self.ename)

emp = Employee()
emp.getEmpDetails()
print("In Out side of the class")
print("eno Value :",emp.eno)
print("ename Value :",emp.ename)

OP:
---
Inside Constructor
eno value : 111
ename value : AAA
Inside Instance Method
eno Value : 111
ename Value : AAA
In Out side of the class
eno Value : 111
ename Value :AAA

2. Static Variables:
---------------------
If any variable is not having changes in its value from one instance to another
instance then that variable is called as Static variable.

In general, in Python applications, we are able to access static variables either


by using class name or by using object reference variables.

In python applications, we are able to declare static variables in the following


locations.
1. In out side of the methods and inside class.
2. Inside constructor by using class name.
3. Inside Instance method by using class name.
4. Inside classmethod[a Method is decvlared with @classmethod decorator] by using
class name and cls variable.
5. Inside static method[a method is declared with @staticmethod decorator] by using
class name.
6. In out side of the class by using class name.
EX:
---
class A:
i = 10
j = 20
def __init__(self):
A.k = 30
A.l = 40
def m1(self):
A.m = 50
A.n = 60

@classmethod
def m2(cls):
A.o = 70
cls.p = 80

@staticmethod
def m3():
A.q = 90

print(A.__dict__)
a = A()
print(A.__dict__)
a.m1()
print(A.__dict__)
A.m2()
print(A.__dict__)
A.m3()
print(A.__dict__)
A.r = 100
print(A.__dict__)
OP:
---
{'i': 10, 'j': 20, .... }
{'i': 10, 'j': 20, 'k': 30, 'l': 40 .... }
{'i': 10, 'j': 20, 'k': 30, 'l': 40, 'm': 50, 'n': 60 ....}
{'i': 10, 'j': 20, 'k': 30, 'l': 40, 'm': 50, 'n': 60, 'o': 70, 'p': 80,...}
{'i': 10, 'j': 20, 'k': 30, 'l': 40, 'm': 50, 'n': 60, 'o': 70, 'p': 80, 'q':
90,...}
{'i': 10, 'j': 20, 'k': 30, 'l': 40, 'm': 50, 'n': 60, 'o': 70, 'p': 80, 'q': 90,
'r': 100,.....}

In Python applications, we are able to access static variables in the following


locations.

1. In out side of the class by using class name and by using refverence variable.
2. Inside the constructor by using Class Name
3. Inside Instance method by using class name and self variable.
4. Inside classmethod by using class name and by using cls variable.
5. Inside static method by using class name.

EX:
---
class A:
i = 10
j = 20
def __init__(self):
print("Inside Constructor Class Name :",A.i," ",A.j)
def m1(self):
print("Inside Instance Method Class Name :",A.i," ",A.j )
print("Inside Instance Method Self Var :",self.i," ",self.j )
@classmethod
def m2(cls):
print("Inside class method Class Name :",A.i," ",A.j)
print("Inside class method cls var :",cls.i," ",cls.j)
@staticmethod
def m3():
print("Inside static method class name :",A.i," ",A.j)
a = A()
a.m1()
a.m2()
a.m3()
print("Out side of the Class Ref Var :",a.i," ",a.j)
print("Out Side of The Class Class Name :",A.i," ",A.j)
OP:
---
Inside Constructor Class Name : 10 20
Inside Instance Method Class Name : 10 20
Inside Instance Method self var : 10 20
Inside class method Class Name : 10 20
Inside class method cls var : 10 20
Inside static method class name : 10 20
Out side of the Class Ref Var : 10 20
Out Side of The Class Class Name : 10 20

3. Local variables
-------------------
--> These variables are declared insid methods, these variables are utilized for
temporary purpose.
--> Local variables are created the moment when we access the respective method and
local variables are destroyed the moment when we complete the execution of the
respective method.
--> Loical variables are having scope upto the respective method only, they are not
having scope in out side of the methods.
EX:
---
class A:
def add(self):
i = 10
j = 20
print("ADD : ",(i+j))
def sub(self):
i = 10
j = 5
print("SUB : ",(i-j))
def mul(self):
i = 10
j = 5
print("MUL : ",(i*j))
a = A()
a.add()
a.sub()
a.mul()

OP:
---
ADD : 30
SUB : 5
MUL : 50

Methods in Python:
-------------------
In Python classes, method is a set of instructions representing a particular action
or behaviour of an entity.

There are three types of methods in Python.


1. Instance Method.
2. Class Method
3. Static Method

1. Instance Method:
--------------------
--> If any Python method is performing operations on atleast one instance variable
then that method is called as Instance method.

--> Inside instance methods, we need to pass atleast self parameter, because, by
using self parameter only we are able to manipulate instance variables.

--> In Python applications, we are able to access instance methods by using object
reference variables in out side of the methods, but, inside the methods we can use
"self" parameter.
EX:
---
class Employee:
def __init__(self, eid, ename, esal):
self.eid = eid
self.ename = ename
self.esal = esal
def setAccountDetails(self, accNo, accHolderName, accBranch, bankName):
self.accNo = accNo
self.accHolderName = accHolderName
self.accBranch = accBranch
self.bankName = bankName
def setAddressDetails(self, hno, street, city, state, country):
self.hno = hno
self.street = street
self.city = city
self.state = state
self.country = country
def getEmployeeDetails(self):
print("Employee Details ")
print("---------------------------")
print("Employee Id :",self.eid)
print("Employee Name :",self.ename)
print("Employee Salary :",self.esal)
print()
print("Account Details")
print("-------------------")
print("Account Number :",self.accNo)
print("Account Holder Name :",self.accHolderName)
print("Account Branch :",self.accBranch)
print("Account Bank :",self.bankName)
print()
print("Address Details")
print("---------------------")
print("House Number :",self.hno)
print("Street :",self.street)
print("City :",self.city)
print("State :",self.state)
print("Country :",self.country)

emp = Employee("E-111", "AAA", 5000)


emp.setAccountDetails("abc123", "AAA","Ameerpet", "ICICI Bank")
emp.setAddressDetails("102, 128/3rt", "MG Road", "Hyd", "Telangana", "India")
emp.getEmployeeDetails()
OP:
---
Employee Details
---------------------------
Employee Id : E-111
Employee Name : AAA
Employee Salary : 5000

Account Details
-------------------
Account Number : abc123
Account Holder Name : AAA
Account Branch : Ameerpet
Account Bank : ICICI Bank

Address Details
---------------------
House Number : 102, 128/3rt
Street : MG Road
City : Hyd
State : Telangana
Country : India

2. Class Method:
-----------------
--> It is a python method, it will work on class variables[Static Variables].
--> To declare class methods we will use @classmethod decorator.
--> In Python, all class methods are not having "self" parameter, all class methods
are having 'cls' parameter, where ls parameter can be used to access class
variables.
--> In Python classes, we are able to access class methods either by using class
name or by using object referfence variable.
EX:
---
class A:
i = 10
j = 20

@classmethod
def m1(cls):
print("i value :",cls.i)
print("j value :",cls.j)

A.m1()
a = A()
a.m1()

OP:
---
i value : 10
j value : 20
i value : 10
j value : 20

EX:
---
class Customer:
count = 0
def __init__(self):
Customer.count = Customer.count + 1

@classmethod
def getObjectsCount(cls):
print("No of Objects :", cls.count)

cust1 = Customer()
cust2 = Customer()
cust3 = Customer()
cust4 = Customer()
cust5 = Customer()

Customer.getObjectsCount()

OP:
---
No of Objects : 5

3. Static Method:
-----------------
--> It is a Python method, it will not use instance variables and class variables.
--> To declare static methods wed will use @staticmethod decoarator.
--> Static methods are not having self parameter and cls parameter.
--> In python, we are able to access static methods by using class name directly or
by using object reference variable.
EX:
---
class A:
@staticmethod
def m1(i, j):
print("m1()-Method")
print(i," ",j)
A.m1(10,20)
a = A()
a.m1(30,40)

OP:
---
m1()-Method
10 20
m1()-Method
30 40

EX:
---
class Calculator:

@staticmethod
def add(fval, sval):
print("ADD :",(fval + sval))

@staticmethod
def sub(fval, sval):
print("SUB :",(fval - sval))
@staticmethod
def mul(fval, sval):
print("MUL :",(fval * sval))

Calculator.add(10,5)
Calculator.sub(10,5)
Calculator.mul(10,5)

OP:
---
ADD : 15
SUB : 5
MUL : 50

Inheritance In Python:
----------------------
It is a relation between classes, it will bring variables and methods from one
clsas[ Parent class / Super class/ Base Class] to another class[child class / sub
class/ Derived class].

The main advantage of Inheritance is "Code reusability", Declare variables and


methods one time in super class then access that variables and methods in any no of
times in sub classes.

To specify super classes for a sub class then we have to use () along with sub
class name with the super class names specification with , seperator.
Syntax:
-------
class ClassName(SuperClass1, SuperClass2,...SuperClass-n)
{

EX:
---
class Person:
def __init__(self,pname,page,paddr):
self.pname = pname
self.page = page
self.paddr = paddr
def getPersonDetails(self):
print("Name :",self.pname)
print("Age :",self.page)
print("Address :",self.paddr)
class Employee(Person):
def __init__(self,eid,esal,edes,pname,page,paddr):
self.eid=eid
self.esal=esal
self.edes=edes
self.pname = pname
self.page = page
self.paddr = paddr

def getEmployeeDetails(self):
print("Employee Details")
print("--------------------")
self.getPersonDetails()
print("EID :",self.eid)
print("ESAL :",self.esal)
print("EDES :",self.edes)
emp = Employee("E-111", 10000.0,"Manager", "Durga", 28, "Hyd")
emp.getEmployeeDetails()

OP:
---
Employee Details
--------------------
Name : Durga
Age : 28
Address : Hyd
EID : E-111
ESAL : 10000.0
EDES : Manager

Note: In the above application, we have provided super class instance variables
initialization in sub class constructor.

Polymorphism:
-------------
Polymorphism is a Greak word, where Poly means Many and Morphism means Structers or
forms.

If one thing is existed in more than one form then it is called as Polymorphism.

The main advantage of Polymorphism is "Flexibility" to develop applications.

EX:
---
class Duck:
def talk(self):
print("Quack..Quack...")

class Dog:
def talk(self):
print("Bow Bow....")

class Cat:
def talk(self):
print("Moew Moew,...")
class Goat:
def talk(self):
print("Myaa Myaa..")

def fn(obj):
obj.talk()

list = [Duck(), Dog(), Cat(), Goat()]


for x in list:
fn(x)

OP:
----
Quack..Quack...
Bow Bow....
Moew Moew,...
Myaa Myaa..

You might also like