PP UNIT 4 (Object Oriented Programming)
PP UNIT 4 (Object Oriented Programming)
oriented programming)
Object oriented concepts in Python
Data Abstraction
Data Encapsulation
Inheritance
Polymorphism
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()
s2=Student("Sruthi",21,90)
s2.talk()
Attributes
Python has two types of attributes
Class attributes
Instance attributes
Class / static attributes
SN Function Description
1 getattr(obj,name,defa It is used to access the attribute of
ult) the object.
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.
abs No match
alias 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
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').
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
a 1 match
^a abc 1 match
bac No match
abc 1 match
No match
^ab (starts
acb
$ - Dollar
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.
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.
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.
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?
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}
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).
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
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.")