0% found this document useful (0 votes)
141 views67 pages

PP UNIT 4 (Object Oriented Programming)

The document discusses object oriented concepts in Python including classes, objects, inheritance, and polymorphism. It provides examples of defining classes with attributes and methods, creating objects, and using inheritance for single inheritance, multilevel inheritance, and multiple inheritance. Specific concepts covered include class and instance attributes, built-in class functions and attributes, and using constructors in inheritance hierarchies. Examples are provided to illustrate key concepts like single, multiple, and multilevel inheritance for applications like students and marks.

Uploaded by

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

PP UNIT 4 (Object Oriented Programming)

The document discusses object oriented concepts in Python including classes, objects, inheritance, and polymorphism. It provides examples of defining classes with attributes and methods, creating objects, and using inheritance for single inheritance, multilevel inheritance, and multiple inheritance. Specific concepts covered include class and instance attributes, built-in class functions and attributes, and using constructors in inheritance hierarchies. Examples are provided to illustrate key concepts like single, multiple, and multilevel inheritance for applications like students and marks.

Uploaded by

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

PP UNIT 4(Object

oriented programming)
Object oriented concepts in Python
 Data Abstraction
 Data Encapsulation
 Inheritance
 Polymorphism

….are the object oriented concepts in python.


Classes and objects..
A class is collection of attributes and actions.
Syntax of defining a class is

class classname(object):
attributes
def __init__(self):
def method1():
def method2():
Classes and objects…
A class definition starts with keyword class and followed by
classname.
After classname,we can give object in brackets followed by :
Object is super class for all the classes in python,we can
give or omit it.
Inside the class with some indentation provide attributes
,constructor and methods.
Attributes are variables which store data.
__init__(self) is constructor which initialises attributes of
class,it takes self as parameter which is the instance of
current class.
Every method also takes self as the first parameter.
Classes and objects…
Object is instance of class
The syntax to create object is..
Object_name=classname()

When object is created ,it allocates memory


internally,and it calls constructor implicitly by
passing address of object as self parameter
to __init__(self)(constructor)
And finally that address is returned to variable
on left hand side.
Example
class Student: Output:
def __init__(self):
self.name=‘NIDHI’ My name is NIDHI
self.age=20 My age is 20
self.marks=89
def talk(self): My marks is 89
print(“My name
is”,self.name)
print(“My age is”,self.age)
print(“My marks
is”,self.marks)
s1=Student()
s1.talk()
Parameterised constructor
class Student:
def __init__(self,n="",a=0,m=0):
Output:
self.name=n My name is Sruthi
self.age=a
self.marks=m
My age is 21
def talk(self): My marks is 90
print("My name is",self.name)
print("My age is",self.age)
print("My marks
is",self.marks)

s2=Student("Sruthi",21,90)
s2.talk()
Attributes
Python has two types of attributes
 Class attributes
 Instance attributes
Class / static attributes

 The variables which are declared within the class


outside the methods are known as static variables
 The data which is common for all the objects is
recommended to represent by using static variables.
 For all the static variables of a class memory will be
allocated only once.
 Static variables of one class we can access within same
class by using class name or by using self
 Static variables of one class we can access outside of
the class by using class name or by using reference variable
name.
class CSStudent:
    stream = 'cse'                  # Class Variable
    def __init__(self,name,roll):
        self.name = name            # Instance Variable
        self.roll = roll            # Instance Variable  
# Objects of CSStudent class
a = CSStudent('Geek', 1)
b = CSStudent('Nerd', 2)
  
print(a.stream)  # prints "cse"
print(b.stream)  # prints "cse"
print(a.name)    # prints "Geek"
print(b.name)    # prints "Nerd"
print(a.roll)    # prints "1"
print(b.roll)    # prints "2”  
# Class variables can be accessed using class
# name also
print(CSStudent.stream) # prints "cse"
 Variables which are declared within the class by using
self or by using reference variable are known as non static
variables
 The data which is separate for every object is
recommended to represent by using non static variables
 Non static variables of a class memory will be allocated
within the object.
 We can create n number of objects for a class so that n
number of times memory will be allocated for non static
variables
 Non static variables of a class we can access within the
same class by using self. Or by using reference variable.
Ex: Output:
class x: 1000
def m1(self): 2000
self.a=1000 3000
self.b=2000 4000
def display(self): 1000
print(self.a) 2000
print(self.b)
X1=x()
X1.m1()
X1.display()
X1.a=3000
X1.b=4000
X1.display()
X2=x()
X2.m1()
X2.display()
Python In-built class functions

SN Function Description
1 getattr(obj,name,defa It is used to access the attribute of
ult) the object.

2 setattr(obj, It is used to set a particular value to


name,value) the specific attribute of an object.

3 delattr(obj, name) It is used to delete a specific


attribute.

4 hasattr(obj, name) It returns true if the object contains


some specific attribute.
Ex
class Student:  
def __init__(self,name,id,age):  
self.name = name  
self.id = id  
self.age = age  
s = Student("John",101,22)  #creates the object of the class Student  
print(getattr(s,'name'))  #prints the attribute name of the object s
setattr(s,"age",23)   # reset the value of attribute age to 23  
print(getattr(s,'age'))   # prints the modified value of age  
print(hasattr(s,'id'))   # prints true if the student contains the attribute 
with name id 
delattr(s,'age')   # deletes the attribute age  
print(s.age)  # this will give an error since the attribute age has 
been deleted  
output
John
23
True
AttributeError: 'Student' object has no attribute 'age'
Built-in class attributes
A python class also contains some built-in class
attributes which provide information about the class.
SN Attribute Description
1 __dict__ It provides the dictionary containing the
information about the class namespace.

2 __doc__ It contains a string which has the class


documentation
3 __name__ It is used to access the class name.
4 __module__ It is used to access the module in which, this
class is defined.
5 __bases__ It contains a tuple including all base classes.
EX
class Student:  
def __init__(self,name,id,age):  
self.name = name 
self.id = id
self.age = age  
def display_details(self):  
print("Name:%s, ID:%d, age:%d"%(self.name,self.id))  
s = Student("John",101,22)  
print(s.__doc__)  
print(s.__dict__)  
print(s.__module__)  
Output 
None
{'name': 'John', 'id': 101, 'age': 22}
__main__
Inheritance
 In inheritance, the child class acquires the properties
and can access all the data members and functions defined
in the parent class.
 A child class can also provide its specific
implementation to the functions of the parent class.
 Inheritance provides code reusability to the program
because we can use an existing class to create a new class
instead of creating it from scratch.
Syntax
class  derived-class(base class):  
<class-suite>   
 In python, a derived class can inherit base class by just
mentioning the base in the bracket after the derived class
name.
 A class which is extended by another class is known as
a super class or base class
 A class which is extending another class is known as a
Single Inheritance
The concept of inheriting the properties from only one
class into another class.
Ex
class A:
def m1(self):
print(“m1 method”)
class B(A):
def m2(self):
print(“m2 method”)
b=B()
b.m1()
b.m2()
Multilple Inheritance

The features of all the base classes are inherited into the
derived class.
Ex
class x:
def m1(self): Output
print(“in m1 of x”) in m1 of x
class y: in m2 of y
def m2(self): in m3 of z
print(“in m2 of y”)
class z(x,y):
def m3(self):
print(“in m3 of z”)
z1=z()
z1.m1()
z1.m2()
Z1.m3()
Multilevel Inheritance
The features of the base class and the derived class is
inherited into the new derived class.
Ex
class X:
def m1(self):
print(“in m1 of x”)
class Y(X):
def m2(self):
print(“in m2 of y”)
class Z(Y):
def m3(self):
print(“in m3 of z”)
Z1=Z()
Z1.m1()
Z1.m2()
Z1.m3()
Constructors in Inheritance
class A:
def __init__(self,x):
self.a=x
class B(A):
def __init__(self,x,y):
self.b=y
A.__init__(self,x)
class C(B):
def __init__(self,x,y,z):
self.c=z
B.__init__(self,x,y)
def disp(self):
print(self.a,self.b,self.c)
obj=C(1,2,3)
obj.disp()
Inheritance programs
 Student->Marks
 Student->Marks->Sports
 Shape->Rectangle

Shape->Triangle
 Person->Employee

Salary->Employee
#program for single def display(self):
inheritance print(“Roll no=“,self.rollno)
class Student: print(“Name=“,self.name)
def __init__(self,rno,n): print(“Percentage=“,self.p)
self.rollno=rno s1=Marks(24,”Nidhi”,
self.name=n [69,70,89,56,96,99])
class Marks(Student): s1.percentage()
s1.display()
def __init__(self,rno,n,m):
self.marks=m
Output:
Student.__init__(self,rno,n) Rollno=24
def percentage(self): Name=Nidhi
for i in Percentage=79.83
range(len(self.marks)):
total+=self.marks[i]
self.p=total/len(self.marks)
#program for multilevel class Sports(Marks):
def __init__(self, rno,n,m,w,h):
inheritance self.weight=w
class Student: self.height=h
Marks.__init__(self, rno,n,m):
def __init__(self,rno,n): def display(self):
self.rollno=rno print(“Roll no=“,self.rollno)
print(“Name=“,self.name)
self.name=n print(“Percentage=“,self.p)
print(“weight=“self.weight)
class Marks(Student): print(“height=“self.height)
def __init__(self,rno,n,m): s1=Sports(24,”Nidhi”,[69,70,89,56,96,99],60,165)
s1.percentage()
self.marks=m s1.display()
Student.__init__(self,rno,n)
Output:
def percentage(self): Rollno=24
for i in range(len(self.marks)): Name=Nidhi
Percentage=79.83
total+=self.marks[i] Weight=60
self.p=total/len(self.marks) Height=165
#Program for Hirarchial inheritance def area(self):
class Shape:
def __init__(self,l,b): print(“Area=“,0.5*self.lengt
self.length=l h*self.breadth)
self.breadth=b
class Rectangle(Shape): r=Rectangle(4,5)
def __init__(self,l,b): r.area()
Shape.__init__(self,l,b) t=Triangle(3,2)
def area(self): t.area()

print(“Area=“,self.length*self.breadt Output:
h) Area=20
class Triangle(Shape): Area=3
def __init__(self,l,b):
Shape.__init__(self,l,b)
#program for multiple class Employee(Person,Salary):
inheritance def __init(self,n,a,b,d_a,hr_a):
class Person: Person.__init__(self,n,a)
Salary.__init__(self,b,d_a,hr_a)
def__init__(self,n,a): def display():
self.name=n print(“Name=“self.name)
self.age=a print(“Age=“self,age)
class Salary: print(“Gross salary=“self.findgross())
e1=Employee(“Ram”,35,25000,3000,1500
def __init__(self,b,d_a,hr_a): )
self.basic=b e1.display()
self.da=d_a
self.hra=hr_a Output:
Name=Ram
def findgross(self):
Age=35
Gross salary=29500
self.gross=self.basic+self.da+s
elf.hra
Overloading and Overriding
Overloading
Defining multiple methods with the same name with
different number of parameters with in the same class or
one is in super class and other is in sub class.
Ex
class X:
def product(a,b):
p=a*b
print(p)
def product(a,b,c):
p=a*b*c
print(p)
X1=X()
X1.product(4,5) # produces an error
 python doesn’t support method overloading but we can
make the same function work differently that is as per the
arguments.
EX
class X:
def m(self,*args):
self.j=1
for i in args:
self.j=self.j*i
print(self.j)
X1=X()
X1.m(10,20)
X1.m(2,3,4)
class A:
def printinf(self,a,b):
print(a,b)
x=A()
x.printinf(3,8)
x.printinf(4.5,False)
x.printinf(8+7j,[3,4,5])
Overriding
 The parent class method is defined in the child class
with some specific implementation, then the concept is
called method overriding.
 We may need to perform method overriding in the
scenario where the different definition of a parent class
method is needed in the child class.
Ex
class Parent:  
def speak(self):  
print("speaking telugu")  
class Child(Parent):  
def speak(self):  
print(“speaking english")  
c = Child()  
c.speak()  
Operator overloading
Consider that we have two objects which are a physical
representation of a class (user-defined data type) and we
have to add two objects with binary ‘+’ operator it
throws an error, because compiler don’t know how to
add two objects. So we define a method for an operator
and that process is called operator overloading. We can
overload all existing operators but we can’t create a new
operator. To perform operator overloading, Python
provides some special function or magic function that is
automatically invoked when it is associated with that
particular operator. For example, when we use +
operator, the magic method __add__ is automatically
invoked in which the operation for + operator is defined.
Example
# Python Program illustrate how 
# to overload an binary + operator
  
class A:
    def __init__(self, a):
        self.a = a
  
    # adding two objects 
    def __add__(self, o):
        return self.a + o.a 
ob1 = A(1)
ob2 = A(2)
ob3 = A(“OH")
ob4 = A(“GOD")
  
print(ob1 + ob2)
print(ob3 + ob4)
Output:
3
OHGOD
Data hiding
 Abstraction is an important aspect of object-oriented
programming.
 In python, we can also perform data hiding by adding
the double underscore (___) as a prefix to the attribute
which is to be hidden.
 After this, the attribute will not be visible outside of the
class through the object.
Ex
class My class:
def __init__(self):
self.__y=3
m=Myclass()
print(m.y) # produces an error ie; Attribute Error
Method Resolution Order(MRO)
# Python program showing
# how MRO works
  
class A:
    def reply(self):
        print(" In class A")
class B(A):
    def reply(self):
        print(" In class B")
  
r = B()
r.reply()
Output:
In class B
MRO
In the above example the methods that are
invoked is from class B but not from class A,
and this is due to Method Resolution
Order(MRO).
The order that follows in the above code
is- class B - > class A
In multiple inheritances, the methods are
executed based on the order specified while
inheriting the classes.
# Python program showing
# how MRO works
  
class A:
    def reply(self):
        print(" In class A")
class B(A):
    def reply(self):
        print(" In class B")
class C(A):
    def reply(self):
        print("In class C")
  
# classes ordering
class D(B, C):
    pass
     
r = D()
r.reply()
Output:
In class B
Regular expressions
 A Regular Expression is a string that contains symbols
and characters to find and extract the information needed
by us.
 A Regular expression helps us to search information,
match, find and split information as per our requirements.
 It is also called regex.
 python provides re module, it contains the methods
like compile(), search(), match(), findall(), split() etc are used
in finding the information in the available data.
A pattern defined using RegEx can be used to match against a
string.

Expression String Matched?

abs No match

alias Match

^a...s$ abyss Match

Alias No match

An abacus No match
The Regular Expressions are used to perform the following
operations.
 Matching strings
 Searching for strings
 Finding all strings
 Splitting a string into pieces
 Replacing strings
 The match() method searches in the beginning of the
string and if the matching string is found, it returns a object
that contains the resultant string, otherwise returns None.
We can access the returned object using group() method.
 The search() method searches the string from
beginning till the end and returns the first occurrence of
the matching string otherwise returns None. group()
method is used to retrieve the string.
 The findall() method splits the string according to
regular expression and returns list object, otherwise
returns empty list, retrieve the result using for loop.
Sequence characters in Regular Expressions
Character Description
\d represents any digit(0-9)
\D represents any non digit
\s represents white space(\t,\n)
\S represents non whitespace
\w represents any alphanumeric(A-Z,a-z,0-9)
\W represents any non alphanumeric
\b represents a space around words
\A matches only at start of the string
\z matches only at end of the string
Modifiers in Regular Expressions
Quantifiers in Regular Expressions
Character Description
+ one or more occurrences of the preceding expression
* Zero or more repetitions of the preceding expression
? Zero or one repetition of the preceding expression
{m} Exactly m occurences
{m,n} from m to n, m defaults to 0, n to infinity
Special characters
Character Description
\ escape special characters nature
. Matches any character except new line
^ matches beginning of a string
$ matches end of a string
[…] set of possible characters.
[^…] matches every character except the ones inside
brackets
(…) matches the regular expression inside the
parenthesis
[] - Square brackets

 Square brackets specifies a set of characters


you wish to match.

Expression String Matched?

a 1 match

ac 2 matches
[abc]
Hey Jude No match

abc de ca 5 matches
 You can also specify a range of characters
using - inside square brackets.
[a-e] is the same as [abcde].
[1-4] is the same as [1234].
[0-39] is the same as [01239].
 You can complement (invert) the character set
by using caret ^ symbol at the start of a
square-bracket.
[^abc] means any character except a or b or c.
[^0-9] means any non-digit character.
. - Period
 A period matches any single character (except
newline '\n').

Expression String Matched?

a No match

ac 1 match

.. acd 1 match

2 matches
acde (contains 4
^ - Caret
 The caret symbol ^ is used to check if a
string starts with a certain character

Expression String Matched?

a 1 match

^a abc 1 match

bac No match

abc 1 match

No match
^ab (starts
acb
$ - Dollar

 The dollar symbol $ is used to check if a


string ends with a certain character.

Expression String Matched?

a 1 match

a$ formula 1 match

cab No match
* - Star
 The star symbol * matches zero or more
occurrences of the pattern left to it.

Expression String Matched?

mn 1 match

man 1 match

maaan 1 match
ma*n
No match (a is
main not followed
by n)
+ - Plus
 The plus symbol + matches one or more
occurrences of the pattern left to it.

Expression String Matched?

No match
mn (no a charact
er)

man 1 match

maaan 1 match
ma+n
No match (a
is not
main
? - Question Mark
 The question mark symbol ? matches zero or
one occurrence of the pattern left to it.

Expression String Matched?

mn 1 match

man 1 match

No match (more
maaan than
ma?n one a character)

No match (a is
main not followed by
n)
{} - Braces
 {n,m} This means at least n, and at
most m repetitions of the pattern left to it.
Expression String Matched?

abc dat No match

abc daat 1 match (at daat)

2 matches
a{2,3} aabc daaat (at aabc and daa
at)

2 matches
aabc daaaat (at aabc and daa
aat)
RegEx [0-9]{2, 4}

Expression String Matched?

1 match (match
ab123csde
at ab123csde)

2 matches
[0-9]{2,4}
12 and 345673 (at 12 and 34567
3)

1 and 2 No match
| - Alternation
 Vertical bar | is used for alternation
(or operator).

Expression String Matched?

cde No match

1 match (match
ade
a|b at ade)

3 matches
acdbea
(at acdbea)
() - Group
 Parentheses () is used to group sub-patterns.
 For example, (a|b|c)xz match any string that
matches either a or b or c followed by xz

Expression String Matched?

ab xz No match

1 match (match
abxz
(a|b|c)xz at abxz)

2 matches
axz cabxz
(at axzbc cabxz)
Modifiers Patterns.
Programs using match() function
Ex 1
import re
line = "Every thing is planned"
patten ='Every'
m =re.match(patten,line)
if m:
print("matched at the starting")
print (m.group())
else:
print("not matched")
EX 2
import re
str = “man sun mop run”
result= re.match(r’m\w\w’,str)
print(result.group())
Programs using search() function
EX 1
import re
str=“one two three four five six seven 8 9 10”
result=re.search(r’\b\w{5}\b’,str)
print(result.group())
EX 2
import re
str=“man sun mop run”
result = re.search(r’m\w\w’,str)
if result:
print(result.group())
Ex 3
import re
regex=re.compile(r"\d{10}")
#compile function checks whether the pattern defined
correctly or not, #then it internally creates regex object
while True:
mobno=input("enter mobile number")
if len(mobno)==10:
result=regex.search(mobno)
if result:
print("valid mobile number")
break
else:
print("invalid mobile number")
Ex 4
import re
regex=re.compile(r"(\w+) World")
result=regex.search("Hello world is the easiest World")
if result:
print("match at index",result.start(),result.end())
Ex 5
import re
pattern = "this"
text = "in this world nothing is permanent"
match = re.search(pattern, text)
s = match.start()
e = match.end()
print(s)
print(e)
Python has a module named re to work with RegEx

import re
pattern = '^a...s$'
test_string = 'abyss'
result = re.match(pattern, test_string)
if result:
print("Search successful.")
else:
print("Search unsuccessful.")

You might also like