Unit3py 240928091622 0ea1eac8
Unit3py 240928091622 0ea1eac8
Unit3py 240928091622 0ea1eac8
OOP Concepts in
Python
Object and classes , Defining classes
for objects * UML Class diagram *
Immutable Objects vs. Mutable Objects,
Hiding data fields * Class abstraction and
encapsulation * Object-Oriented Thinking ,
The str Class * Inheritance and
Polymorphism * Super classes and Sub
classes , overriding methods * Object class
, Polymorphism and Dynamic Binding *
The isinstance Function , Class
Relationships.
Object and classes
Python is an object oriented programming
language.
An object is simply a collection of data
(variables) and methods (functions) that act on those
data. Similarly, a class is a blueprint for that object.
We can think of class as a sketch (prototype)
of a house. It contains all the details about the
floors, doors, windows etc. Based on these
descriptions we build the house. House is the object.
Classes
• A python class uses variables to store data fields and
defines methods to perform actions.
• A class is also known as template or blueprint
• To create a class, use the keyword - class
• Attributes or data fields are the variables that belong
to a class
• Attributes are always public and can be accessed using
dot(.) operator
Objects
• An object represents an entity in the real world that can be
distinctly identified.
• An object consists of:
dataFieldName: dataFieldType
Name :str
Rollno: integer Data Fields
Department :str
.
.
.
.etc
Findtotal(m1,m2,m3)
The method definition in the class
always has the special self parameter,
class implementation
Class’s Clients use the
Contract class through
Class
(headers of the class’s
initializer and contract
methods
Example:
>>> s=“ program”
>>>s[2] -- o
>>>s[6] -- m
>>> s[0] -- p
>>> s[7] -- Out of range
• Python also allows the use of negative numbers as index to
reference positions relative to the end of the string
Example:
>>> s=“program”
>>> s[-1]
>>> s[-4]
(ii) Slicing Operator:
The slicing operator returns a slice of the string
syntax : Stringname [start:end]
Example:
>>> s=“welcome”
>>> s[0:4] --- welc
>>> s[1:-1] --- elcom
>>> s[5:-5] ---
Functions for strings
• max(stringname) --- Returns largest number among given
string
>>> s=“welcome”
>>> max(s) --- w
• min(stringname) --- Returns smallest number among given
string
>>> s=“welcome”
>>> min(s) --- e
• len(stringname) ---- Returns length of the given string
>>> s=“welcome”
>>> len(s) --- 7
List operators
• List having more operation like string ( ‘ + ‘ and ‘ * ‘ ), that is
concatenation, in and not in
• Following basic operation performed in list:
Concatenation (+)
Repetition (*)
Membership (in)
• Concatenation is the process of combine two list elements (+)
>>> “we” + “come”
“welcome”
• To repeat the list elements in specified number of time (Repetition) (*)
>>> “wel” * 3
“welwelwel”
• Membership – To find specified elements is in the list or not
>>> w in “welcome”
True
Converting string or methods
• capitalize() ---- Converts the first character to upper case
>>> s=“kncet”
>>> s.capitalize() ---- Kncet
• count() ---- Returns the number of times a specified value occurs in a
string
>>>s=“kncet”
>>>s.count(“k”) ---- 1
• title() ----Converts the first character of each word to upper case
>>> s=“welcome hai”
>>> s.title() ---- Welcome Hai
• lower() ---- Converts a string into lower case
>>> s=“KNCET”
>>>s=“kncet”
>>> s=“knceT”
>>>s=“hai hello”
>>>s.replace(“hai”,”kncet”)
Testing Strings
• isalnum() -- Returns true if all characters in the strings are
alphanumeric
>>> a=“wel123”
>>> a.alnum() ---- True
• isalpha() -- Returns True if all characters in string are in
the alphabet
>>> a=“wel123”
>>> a.alpha() ---- False
• islower() -- Returns true if all characters in the string are
lower case
>>> a=“welcome”
>>> a.islower() ---- True
• isspace() --- Returns true if this contains only whitespace
characters
>>> a=“ “
>>> a=“welcome”
Example:
>>> s="kncet"
>>> for i in s:
print(i)
Inheritance
• Inheritance is an important aspect of the object-oriented
paradigm.
• The method of inheriting the properties of parent class into a
child class is known as inheritance.
• Inheritance provides code reusability to the program
• Types Of Inheritance
--- Single level
--- Multi level
--- Multiple
--- Hierarchical
Base class
Extends
Derived Class
SINGLE INHERITANCE:
• Classes are represented as boxes with the class name on top.
• The inheritance relationship is represented by an arrow from the
derived class pointing to the base class.
• The word extends is usually added to the arrow.
Super classes
• The class from which a class inherits is called the super class
class super_class_name:
Attributes
Methods
Subclasses
• A class which inherits from a super class is called a subclass.
• The child class acquires the properties and can access all the data
members and functions defined in the parent class.
• Syntax:
<class-suite>
Child
class parent1:
def add(self):
print(“Addition”)
class parent2:
def sub(self):
print(“Subtraction”)
class child( parent1, parent2):
def mul (self):
print (“Multiplication”)
super().add()
super().sub()
a=child()
Multilevel Inheritance
• When a child class becomes a parent class for
another child class.
Parent 1
Child 1
Child 2
class parent:
def add(self):
print(“Addition”)
class child1(parent):
def sub(self):
print(“Subtraction”)
class child2( child1):
def mul (self):
print (“Multiplication”)
super().add()
super().sub()
a=child2()
Hierarchical Inheritance:
Hierarchical Inheritance:
When more than one derived classes are
created from a single base,
this type of inheritance is called
hierarchical inheritance.
In this program, we have a parent (base)
class and two child (derived) classes.
class Parent:
def func1(self):
print("This function is in parent class.")
# Derived class1
class Child1(Parent):
def func2(self):
print("This function is in child 1.")
# Derivied class2
class Child2(Parent):
def func3(self):
print("This function is in child 2.")
object1 = Child1()
object2 = Child2()
object1.func1()
object1.func2()
object2.func1()
object2.func3()
Method Overriding
• To override a method, the method must be defined in the
subclass using the same header as in its super class.
• When a method in a subclass has the same name, same
parameters or signature and same return type(or sub-type)
as a method in its super-class, then the method in the
subclass is said to override the method in the super-class.
Example program:
class parent ():
def add(self,x,y):
z=x+y
print (z)
class child (parent):
def add(self, x, y):
z=x+y
print (z)
a=child()
a.add(30,20)
a.add(40,20)
Polymorphism:
What is Polymorphism : The word
polymorphism means having many forms.
In programming, polymorphism means
same function name (but different signatures)
being uses for different types.
Polymorphism is the ability to leverage
the same interface for different underlying
forms such as data types or classes.
This permits functions to use entities of
different types at different times.
Example 1: Polymorphism in addition operator
The + Operator in python perform two
operation
For integer data types, + operator is
used to perform arithmetic addition
operation.
Example:
num1 = 1
num2 = 2
print(num1+num2)
Similarly, for string data types, + operator is
used to perform concatenation.
Example:
str1 = "Python"
str2 = "Programming"
print(str1+" "+str2) output: Python Programming
def language(self):
print("Hindi is the most widely spoken
language of India.")
def type(self):
print("India is a developing country.")
class USA():
def capital(self):
print("Washington, D.C. is the capital of USA.")
def language(self):
print("English is the primary language of USA.")
def type(self):
print("USA is a developed country.")
obj_ind = India()
obj_usa = USA()
for country in (obj_ind, obj_usa):
country.capital()
country.language()
country.type()
Output:
New Delhi is the capital of India.
Hindi is the most widely spoken language of
India.
India is a developing country.
Washington, D.C. is the capital of USA.
English is the primary language of USA.
USA is a developed country.
Dynamic Binding:
class Student:
def __str__(self):
return "Student"
def printStudent(self):
print(self.__str__())
class GraduateStudent(Student):
def __str__(self):
return "Graduate Student"
a = Student()
b = GraduateStudent()
a.printStudent()
b.printStudent()
The Isinstance Function:
The isinstance function can be used to
determine whether an object is an instance of
a class.
The isinstance() function returns True if
the specified object is of the specified type,
otherwise False.
Example:
class myObj:
name = "John"
y = myObj()
x = isinstance(y, myObj)
Class Relationship:
To design classes, you need to explore
the relationships among classes.
The common relationships among
classes are association, aggregation,
composition, and inheritance.
Association:
Association is a general binary
relationship that describes an activity between
two classes.
For example, a student taking a course is
an association between the Student class and
the Course class,
and a faculty member teaching a course
is an association between the Faculty class
and the Course class
Take Teach
Student course faculty
The above UML diagram shows that a
student may take any number of courses,
A faculty member may teach at most
three courses, a course may have from five to
sixty students, and a course is taught by only
one faculty member.
In Python code, you can implement
associations by using data fields and methods.
Example:
class Student:
#Add course to a list
def addCourse(self, course):
class Course:
# Add student to a list
def addStudent(self, student):
def setFaculty(self, faculty):
class Faculty:
# Add course to a list
def addCourse(self, course):
Aggregation and composition
Aggregation and Composition:
Aggregation and Composition are
subsets of association meaning they are
specific cases of association.
Aggregation models has-a relationships.
The owner object is called an
aggregating object,
and its class is called an aggregating
class.
• Aggregation
It implies a relationship where the child
can exist independently of the parent.
In this child class not dependent with
parent class.
Example:
Class (parent)
and Student (child).
Delete the Class and the Students still
exist.
Composition
It implies a relationship where the child
cannot exist independent of the parent.
Here child class dependent with parent
class.
Example:
House (parent)
and Room (child).
Rooms don't exist separate to a House.