SlideShare a Scribd company logo
1 of 86
Unit III
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:
State: It is represented by the attributes of an object.
ex: breed, color, age
Behavior: It is represented by the methods of an object.
ex: bark, sleep, eat
Identity: It gives a unique name to an object.
ex: Name of the dog
Defining a Class in Python
Like function definitions begin with the
def keyword in Python, class definitions begin
with a class keyword.
The first string inside the class is called
docstring and has a brief description about the
class. Although not mandatory.
Syntax:
class class_name(object):
‘’’doc string about the class ‘’’
variable declaration
function definition
Example:
class MyNewClass:
'''This is a docstring. I have created a
new class'''
pass
By using object we access the class
variables and functions.
(OOPS)An object oriented programming
involves the use of objects to create programs.
An object is an entity in real world that can
be distinctly identified.
Example:
student , button, loan ….. Etc
An object’s identity is like a person’s Social
Security number.
Python automatically assigns each object a
unique id for identifying the object at runtime.
An object’s state (also known as its
properties or attributes)
is represented by variables.
A rectangle object has the data fields
width and height,
which are properties that characterize a
rectangle.
Python uses methods to define an object’s
behavior (also known as its actions).
Recall that methods are defined as
functions.
Class Template
Class Name: Circle
Data Fields: radius is _____
Methods:
getArea(),
getPerimeter(),
setRadius()
Defining classes
Here by using variables to store data fields
and defining the methods.
A class provide special method _ _ init _ _
This method known as an initializer, Initilizer
can perform any action, but initializer are
designed to perform initializing action.
Syntax :
Class classname:
initializer
methods
Example:
class student:
'''display student information'''
department="CSE"
def __init__(self,name,Rollno):
self.name=name
self.Rollno=Rollno
def display(self):
print(self.name)
print(self.Rollno)
print(student.department)
Constructing Object
Once a class is defined, you can create
objects from the class with a constructor.
The constructor does two things:
It creates an object in the memory for the
class.
It invokes the class’s _ _init_ _ method to
initialize the object.
All methods, including the initializer, have
the first parameter self.
The self parameter refers to the object that
invokes the method.
The self parameter in the _ _init_ _
method is automatically set to reference,
the object that was just created.
Example:
class student:
'''display student information'''
department="CSE"
def __init__(self,name,Rollno):
self.name=name
self.Rollno=Rollno
def display(self):
print(self.name)
print(self.Rollno)
print(student.department)
s=student("ram",101)
s.display()
UML Class Diagram:
Here class template and objects
standardized using UML( Unified Modeling
Language)notation.
It is a language independent, that is other
programming languages use this same
modeling and notation.
Class field denoted as:
class name:
dataFieldName: dataFieldType
Constructors are shown as:
ClassName(parameterName: parameterType)
Methods are represented as:
methodName(parameterName:
parameterType): returnType
Student # class name
Name :str
Rollno: integer Data Fields
Department :str
.
.
.
.etc
Student (rollno = 101: integer) # Constructor
Display(self, name, deparment) #Methods
Findtotal(m1,m2,m3)
The method definition in the class always
has the special self parameter,
but don’t include it in the UML diagram,
because the client does not need to know
this parameter and does not use this
parameter to invoke the methods.
class student:
'''display student information'''
department="CSE"
def __init__(self,name,Rollno):
self.name=name
self.Rollno=Rollno
def display(self):
print(self.name)
print(self.Rollno)
print(student.department)
s1=student("ram",101)
s2=student(“sam",103)
s1.display()
s2.display()
Mutable vs Immutable Objects in Python:
Whenever an object is instantiated, Pyhton
assigned a unique object id.
The type of the object is defined at the
runtime and it can’t be changed afterwards.
However, it’s state can be changed if it is a
mutable object.
mutable objects can change their state or
contents
Immutable objects can’t change their state
or content.
Immutable Objects :
These are of in-built types like string, tuple
are immutable type in python.
In simple words, an immutable object can’t
be changed after it is created.
class Count:
def __init__(self, count = 0):
self.count = count
def main():
c = Count()
n = 1
m(c, n)
print("count is", c.count)
print("n is", n)
def m(c, n):
c = Count(5)
n = 3
main() # Call the main function
Example:
tuple1 = (0, 1, 2, 3)
tuple1[0] = 4
print(tuple1)
Error :
Traceback (most recent call last):
File
"e0eaddff843a8695575daec34506f126.py",
line 3, in tuple1[0]=4
TypeError: 'tuple' object does not support
item assignment
Mutable Objects :
These are of type list, dict, set . Custom
classes are generally mutable.
Example:
A=[10,20,40]
A[0]=100
Print(A)
Output:
[100,20,40]
Example:
class Count:
def __init__(self, count = 0):
self.count = count
def main():
c = Count()
times = 0
for i in range(100):
increment(c, times)
print("count is", c.count)
print("times is", times)
def increment(c, times):
c.count += 1
times += 1
main() # Call the main function
Output:
count is 100
times is 0
Hiding Data Fields:
Data hiding in Python is the method to
prevent access to specific users in the
application.
Data hiding in Python is done by using a
double underscore before (prefix) the
attribute name.
This makes the attribute private/
inaccessible and hides them from users.
Data hiding helps computer programmers
create classes with unique data sets and
functions by avoiding unnecessary entrance
from other classes in the program.
Advantages of Data Hiding
The objects within the class are
disconnected from irrelevant data.
It prevents programmers from linkage to
incorrect data.
It helps to prevent damage to volatile data
by hiding it from the public.
Example:(public variable access any where)
class JustCounter:
secretCount = 0 # public variable
def count(self):
self.secretCount += 1
print(self.secretCount)
counter = JustCounter()
counter.count()
counter.count()
print(counter.secretCount)
Example:(private variable only access with in
class)
class JustCounter:
__secretCount = 0 # private variable
def count(self):
self.__secretCount += 1
print(self.__secretCount)
counter = JustCounter()
counter.count()
counter.count()
print(counter.__secretCount)
Class Abstraction and Encapsulation
Abstraction and Encapsulation both are
OOP concepts of any object oriented
programming languages.
Both Abstraction and Encapsulation in
OOPs using hiding information to the world.
Class Abstraction:
Abstraction which focuses on the process of
hiding the unwanted details and exposing only
the essential features of a particular object, while
designing time.
Abstraction hides complexity by giving you a
more abstract picture of a complex system.
For example, a class Car would be made up of
an Engine, Gearbox, Steering objects,and many
more components.
To build the Car class, one does not need to
know how the different components work
internally, but only how to interface with them.
Class encapsulation:
Encapsulation also hides data from outside
world, it hide actual data and method
implementation from designer to client.
Encapsulation hide things at
implementation level.
The. user of the class does not need to
know how the class is implemented
The details of implementation are
encapsulated and hidden from the user. This is
known as class encapsulation.
Encapsulation combines data and methods
into a single object and hides the data fields
and method implementation from the user.
class implementation
Class abstraction separates class
implementation from the use of the class.
Class
Class’s
Contract
(headers of
initializer and
methods
Clients use the
class through
the class’s
contract
Object Oriented Thinking
Python uses a programming pattern called
object-oriented programming,
which models concepts using classes and
objects.
This is a flexible, powerful paradigm where
classes represent and define concepts,
while objects are instances of classes.
An object has two characteristics:
 Attributes
 behavior
Example:
A parrot is an object, as it has the following
properties:
• name, age, color as attributes
• singing, dancing as behavior
The str class
• A string (str) is immutable.
• Its content cannot be changed once the string is
created
• The input function returns a string from the
keyboard
• print function displays a string on the monitor
Creating strings
• You can create strings by using str constructor
Example:
s=str() ---- empty string
s=str(“welcome”) ----content
• String can be enclosed by either double or single
quotes
• Although single quotes are more commonly used
Accessing a string
• String can be accessed by index operator and slice operator.
(i) Index operator:
A string is a sequence operator. A character in the string can
be accessed through the index operator
Syntax: stringname[index]
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.lower() ---- kncet
• upper() ---- Converts a string into upper case
>>>s=“kncet”
>>>s.upper() ---- KNCET
• swapcase() ---- lowercase becomes upper case and vice versa
>>> s=“knceT”
>>> s.swapcase() ---- KNCEt
• replace(old,new) ---- Returns a string where a specified value is replaced
with a specified value
>>>s=“hai hello”
>>>s.replace(“hai”,”kncet”)
---- kncet hello
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.isspace() --- True
• isupper() --Returns true if all characters in the string are
upper case
>>> a=“welcome”
>>> a.isupper() ---- False
Comparing Strings
• You can compare strings by using the comparison operators (==,
!=,>,=>,=<,<)
• Python compares strings by comparing their corresponding
characters.
• It does this by evaluating the characters numeric code
• Small letters starts from 97
• Uppercase Letters from 65
Example:
>>> a=“KNCET”
>>> b=“kncet”
>>> a= =b
---- False
Iterating a String
• A string is iterable. This means that you can use a for
loop to traverse all characters in the string sequentially
Example:
>>> s="kncet"
>>> for i in s:
print(i)
---- k n c e t
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
Basic program in class and objects
Class parent:
def fun1(self):
print(“This is function1”)
Class Child():
def fun2(self)
print(“this is function 2”)
Obj=parent()
Obj.fun1()
Obj=child()
Obj.fun2()
Inheritance concept……
Class parent:
def fun1(self):
print(“This is function1”)
Class Child(parent):
def fun2(self)
print(“this is function 2”)
Obj=child()
Obj.fun1()
Obj.fun2()
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.
Base class
Derived Class
Extends
Super classes
• The class from which a class inherits is called the super class
• It is also known as parent class or base class.
• Superclasses are sometimes called ancestors as well
Syntax:
class super_class_name:
Attributes
Methods
Subclasses
• A class which inherits from a super class is called a subclass.
• It is also known as child class.
• The child class acquires the properties and can access all the data
members and functions defined in the parent class.
• Syntax:
class derived-class(base class):
<class-suite>
To create a class that inherits the functionality from
another class, send the parent class as a parameter when creating the
child class
Single Level inheritance:
When a child class inherits only a single parent class.
Example
Example:
Class Addition:
Def add (self):
A=int(input(“Enter the value of :”))
B=int(input(“Enter the value of :”))
C=a+b
Print(“addition:”,c)
Class Subtraction(Addition):
Def sub(self):
A=int(input(“Enter the value of :”))
B=int(input(“Enter the value of :”))
C=a-b
Print(“addition:”,c)
Obj=subtraction()
Obj.add()
Obj.sub()
Multiple Inheritance:
When a child class inherits from more than one
parent class.
Parent 1 Parent 2 Parent 3
Child
Example:
Class Addition:
Def add (self):
A=int(input(“Enter the value of :”))
B=int(input(“Enter the value of :”))
C=a+b
Print(“addition:”,c)
Class Subtraction(Addition):
Def sub(self):
A=int(input(“Enter the value of :”))
B=int(input(“Enter the value of :”))
C=a-b
Print(“addition:”,c)
Class Input(Addition,Subtraction):
Def base(Self):
self.add()
self.sub()
Obj=Input()
Obj.base()
Multilevel Inheritance
• When a child class becomes a parent class for
another child class.
Parent 1
Child 1
Child 2
Example:
Class Addition:
Def add (self):
A=int(input(“Enter the value of :”))
B=int(input(“Enter the value of :”))
C=a+b
Print(“addition:”,c)
Class Subtraction(Addition):
Def sub(self):
A=int(input(“Enter the value of :”))
B=int(input(“Enter the value of :”))
C=a-b
Print(“addition:”,c)
Class calfun(Subtraction):
Def call(Self):
self.add()
self.sub()
Obj=calfun()
Obj.call()
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.
Example:
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)
Example
Class ram:
def project(self):
Print(“online shopping management system”)
Class sam(ram):
def project(self):
super().project()
Print(“online voting system”)
Obj=sam()
Obj.project()
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
This is one of the most simple occurrences of
polymorphism in Python.
Here are some functions in Python which are
compatible to run with multiple data types.
One such function is the len() function. It can
run with many data types in Python.
Example:
print(len("Programiz"))
print(len(["Python", "Java", "C"]))
print(len({"Name": "John", "Address": "Nepal"}))
Polymorphism and dynamic Binding:
We can use the concept of polymorphism
while creating class methods as Python allows
different classes to have methods with the
same name.
Polymorphism means that an object of a
subclass can be passed to a parameter of a
super class type.
A method may be implemented in several
classes along the inheritance chain. is also
called method overriding.
Python decides which method is invoked
at runtime. This is known as dynamic binding.
Example:
class India():
def capital(self):
print("New Delhi is the capital of India.")
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.
Syntax:
Isinstanec(object,type)
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.

More Related Content

Similar to Unit - 3.pptx

Classes, objects and methods
Classes, objects and methodsClasses, objects and methods
Classes, objects and methodsfarhan amjad
 
Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02Getachew Ganfur
 
C++ Programming Course
C++ Programming CourseC++ Programming Course
C++ Programming CourseDennis Chang
 
Introduce oop in python
Introduce oop in pythonIntroduce oop in python
Introduce oop in pythontuan vo
 
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲Mohammad Reza Kamalifard
 
Object Oriented Programming with C#
Object Oriented Programming with C#Object Oriented Programming with C#
Object Oriented Programming with C#SyedUmairAli9
 
C++ppt. Classs and object, class and object
C++ppt. Classs and object, class and objectC++ppt. Classs and object, class and object
C++ppt. Classs and object, class and objectsecondakay
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfacesmadhavi patil
 
Basic_concepts_of_OOPS_in_Python.pptx
Basic_concepts_of_OOPS_in_Python.pptxBasic_concepts_of_OOPS_in_Python.pptx
Basic_concepts_of_OOPS_in_Python.pptxsantoshkumar811204
 
classandobjectunit2-150824133722-lva1-app6891.ppt
classandobjectunit2-150824133722-lva1-app6891.pptclassandobjectunit2-150824133722-lva1-app6891.ppt
classandobjectunit2-150824133722-lva1-app6891.pptmanomkpsg
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Threeamiable_indian
 

Similar to Unit - 3.pptx (20)

Lecture 4. mte 407
Lecture 4. mte 407Lecture 4. mte 407
Lecture 4. mte 407
 
Python classes objects
Python classes objectsPython classes objects
Python classes objects
 
Classes, objects and methods
Classes, objects and methodsClasses, objects and methods
Classes, objects and methods
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
 
Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02
 
C++ Programming Course
C++ Programming CourseC++ Programming Course
C++ Programming Course
 
Introduce oop in python
Introduce oop in pythonIntroduce oop in python
Introduce oop in python
 
Templates
TemplatesTemplates
Templates
 
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
 
Module IV_updated(old).pdf
Module IV_updated(old).pdfModule IV_updated(old).pdf
Module IV_updated(old).pdf
 
Object Oriented Programming with C#
Object Oriented Programming with C#Object Oriented Programming with C#
Object Oriented Programming with C#
 
C++ppt. Classs and object, class and object
C++ppt. Classs and object, class and objectC++ppt. Classs and object, class and object
C++ppt. Classs and object, class and object
 
Spsl vi unit final
Spsl vi unit finalSpsl vi unit final
Spsl vi unit final
 
Spsl v unit - final
Spsl v unit - finalSpsl v unit - final
Spsl v unit - final
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
 
Basic_concepts_of_OOPS_in_Python.pptx
Basic_concepts_of_OOPS_in_Python.pptxBasic_concepts_of_OOPS_in_Python.pptx
Basic_concepts_of_OOPS_in_Python.pptx
 
classandobjectunit2-150824133722-lva1-app6891.ppt
classandobjectunit2-150824133722-lva1-app6891.pptclassandobjectunit2-150824133722-lva1-app6891.ppt
classandobjectunit2-150824133722-lva1-app6891.ppt
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Three
 
Python-Classes.pptx
Python-Classes.pptxPython-Classes.pptx
Python-Classes.pptx
 
My c++
My c++My c++
My c++
 

More from Kongunadu College of Engineering and Technology (19)

Unit V - ppt.pptx
Unit V - ppt.pptxUnit V - ppt.pptx
Unit V - ppt.pptx
 
C++ UNIT4.pptx
C++ UNIT4.pptxC++ UNIT4.pptx
C++ UNIT4.pptx
 
c++ Unit I.pptx
c++ Unit I.pptxc++ Unit I.pptx
c++ Unit I.pptx
 
c++ Unit III - PPT.pptx
c++ Unit III - PPT.pptxc++ Unit III - PPT.pptx
c++ Unit III - PPT.pptx
 
c++ UNIT II.pptx
c++ UNIT II.pptxc++ UNIT II.pptx
c++ UNIT II.pptx
 
UNIT 1.pptx
UNIT 1.pptxUNIT 1.pptx
UNIT 1.pptx
 
UNIT 4.pptx
UNIT 4.pptxUNIT 4.pptx
UNIT 4.pptx
 
UNIT 5.pptx
UNIT 5.pptxUNIT 5.pptx
UNIT 5.pptx
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
UNIT 3.pptx
UNIT 3.pptxUNIT 3.pptx
UNIT 3.pptx
 
Unit - 1.ppt
Unit - 1.pptUnit - 1.ppt
Unit - 1.ppt
 
UNIT 5.pptx
UNIT 5.pptxUNIT 5.pptx
UNIT 5.pptx
 
Unit - 2.ppt
Unit - 2.pptUnit - 2.ppt
Unit - 2.ppt
 
Unit - 4.ppt
Unit - 4.pptUnit - 4.ppt
Unit - 4.ppt
 
U1.ppt
U1.pptU1.ppt
U1.ppt
 
U2.ppt
U2.pptU2.ppt
U2.ppt
 
U4.ppt
U4.pptU4.ppt
U4.ppt
 
U5 SPC.pptx
U5 SPC.pptxU5 SPC.pptx
U5 SPC.pptx
 
U3.pptx
U3.pptxU3.pptx
U3.pptx
 

Recently uploaded

HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...Call Girls in Nagpur High Profile
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...RajaP95
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).pptssuser5c9d4b1
 

Recently uploaded (20)

Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
 

Unit - 3.pptx

  • 2. 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.
  • 3. 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.
  • 4. 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
  • 5. Objects • An object represents an entity in the real world that can be distinctly identified. • An object consists of: State: It is represented by the attributes of an object. ex: breed, color, age Behavior: It is represented by the methods of an object. ex: bark, sleep, eat Identity: It gives a unique name to an object. ex: Name of the dog
  • 6. Defining a Class in Python Like function definitions begin with the def keyword in Python, class definitions begin with a class keyword. The first string inside the class is called docstring and has a brief description about the class. Although not mandatory. Syntax: class class_name(object): ‘’’doc string about the class ‘’’ variable declaration function definition
  • 7. Example: class MyNewClass: '''This is a docstring. I have created a new class''' pass By using object we access the class variables and functions.
  • 8. (OOPS)An object oriented programming involves the use of objects to create programs. An object is an entity in real world that can be distinctly identified. Example: student , button, loan ….. Etc An object’s identity is like a person’s Social Security number. Python automatically assigns each object a unique id for identifying the object at runtime.
  • 9. An object’s state (also known as its properties or attributes) is represented by variables. A rectangle object has the data fields width and height, which are properties that characterize a rectangle.
  • 10. Python uses methods to define an object’s behavior (also known as its actions). Recall that methods are defined as functions.
  • 11. Class Template Class Name: Circle Data Fields: radius is _____ Methods: getArea(), getPerimeter(), setRadius()
  • 12. Defining classes Here by using variables to store data fields and defining the methods. A class provide special method _ _ init _ _ This method known as an initializer, Initilizer can perform any action, but initializer are designed to perform initializing action. Syntax : Class classname: initializer methods
  • 13. Example: class student: '''display student information''' department="CSE" def __init__(self,name,Rollno): self.name=name self.Rollno=Rollno def display(self): print(self.name) print(self.Rollno) print(student.department)
  • 14. Constructing Object Once a class is defined, you can create objects from the class with a constructor. The constructor does two things: It creates an object in the memory for the class. It invokes the class’s _ _init_ _ method to initialize the object. All methods, including the initializer, have the first parameter self.
  • 15. The self parameter refers to the object that invokes the method. The self parameter in the _ _init_ _ method is automatically set to reference, the object that was just created.
  • 16. Example: class student: '''display student information''' department="CSE" def __init__(self,name,Rollno): self.name=name self.Rollno=Rollno def display(self): print(self.name) print(self.Rollno) print(student.department) s=student("ram",101) s.display()
  • 17. UML Class Diagram: Here class template and objects standardized using UML( Unified Modeling Language)notation. It is a language independent, that is other programming languages use this same modeling and notation.
  • 18. Class field denoted as: class name: dataFieldName: dataFieldType Constructors are shown as: ClassName(parameterName: parameterType) Methods are represented as: methodName(parameterName: parameterType): returnType
  • 19. Student # class name Name :str Rollno: integer Data Fields Department :str . . . .etc Student (rollno = 101: integer) # Constructor Display(self, name, deparment) #Methods Findtotal(m1,m2,m3)
  • 20. The method definition in the class always has the special self parameter, but don’t include it in the UML diagram, because the client does not need to know this parameter and does not use this parameter to invoke the methods.
  • 21. class student: '''display student information''' department="CSE" def __init__(self,name,Rollno): self.name=name self.Rollno=Rollno def display(self): print(self.name) print(self.Rollno) print(student.department) s1=student("ram",101) s2=student(“sam",103) s1.display() s2.display()
  • 22. Mutable vs Immutable Objects in Python: Whenever an object is instantiated, Pyhton assigned a unique object id. The type of the object is defined at the runtime and it can’t be changed afterwards. However, it’s state can be changed if it is a mutable object. mutable objects can change their state or contents Immutable objects can’t change their state or content.
  • 23. Immutable Objects : These are of in-built types like string, tuple are immutable type in python. In simple words, an immutable object can’t be changed after it is created.
  • 24. class Count: def __init__(self, count = 0): self.count = count def main(): c = Count() n = 1 m(c, n) print("count is", c.count) print("n is", n) def m(c, n): c = Count(5) n = 3 main() # Call the main function
  • 25. Example: tuple1 = (0, 1, 2, 3) tuple1[0] = 4 print(tuple1) Error : Traceback (most recent call last): File "e0eaddff843a8695575daec34506f126.py", line 3, in tuple1[0]=4 TypeError: 'tuple' object does not support item assignment
  • 26. Mutable Objects : These are of type list, dict, set . Custom classes are generally mutable. Example: A=[10,20,40] A[0]=100 Print(A) Output: [100,20,40]
  • 27. Example: class Count: def __init__(self, count = 0): self.count = count def main(): c = Count() times = 0 for i in range(100): increment(c, times) print("count is", c.count) print("times is", times) def increment(c, times): c.count += 1 times += 1 main() # Call the main function Output: count is 100 times is 0
  • 28. Hiding Data Fields: Data hiding in Python is the method to prevent access to specific users in the application. Data hiding in Python is done by using a double underscore before (prefix) the attribute name. This makes the attribute private/ inaccessible and hides them from users.
  • 29. Data hiding helps computer programmers create classes with unique data sets and functions by avoiding unnecessary entrance from other classes in the program. Advantages of Data Hiding The objects within the class are disconnected from irrelevant data. It prevents programmers from linkage to incorrect data. It helps to prevent damage to volatile data by hiding it from the public.
  • 30. Example:(public variable access any where) class JustCounter: secretCount = 0 # public variable def count(self): self.secretCount += 1 print(self.secretCount) counter = JustCounter() counter.count() counter.count() print(counter.secretCount)
  • 31. Example:(private variable only access with in class) class JustCounter: __secretCount = 0 # private variable def count(self): self.__secretCount += 1 print(self.__secretCount) counter = JustCounter() counter.count() counter.count() print(counter.__secretCount)
  • 32. Class Abstraction and Encapsulation Abstraction and Encapsulation both are OOP concepts of any object oriented programming languages. Both Abstraction and Encapsulation in OOPs using hiding information to the world.
  • 33. Class Abstraction: Abstraction which focuses on the process of hiding the unwanted details and exposing only the essential features of a particular object, while designing time. Abstraction hides complexity by giving you a more abstract picture of a complex system. For example, a class Car would be made up of an Engine, Gearbox, Steering objects,and many more components. To build the Car class, one does not need to know how the different components work internally, but only how to interface with them.
  • 34. Class encapsulation: Encapsulation also hides data from outside world, it hide actual data and method implementation from designer to client. Encapsulation hide things at implementation level. The. user of the class does not need to know how the class is implemented The details of implementation are encapsulated and hidden from the user. This is known as class encapsulation.
  • 35. Encapsulation combines data and methods into a single object and hides the data fields and method implementation from the user. class implementation Class abstraction separates class implementation from the use of the class. Class Class’s Contract (headers of initializer and methods Clients use the class through the class’s contract
  • 36. Object Oriented Thinking Python uses a programming pattern called object-oriented programming, which models concepts using classes and objects. This is a flexible, powerful paradigm where classes represent and define concepts, while objects are instances of classes. An object has two characteristics:  Attributes  behavior
  • 37. Example: A parrot is an object, as it has the following properties: • name, age, color as attributes • singing, dancing as behavior
  • 38. The str class • A string (str) is immutable. • Its content cannot be changed once the string is created • The input function returns a string from the keyboard • print function displays a string on the monitor
  • 39. Creating strings • You can create strings by using str constructor Example: s=str() ---- empty string s=str(“welcome”) ----content • String can be enclosed by either double or single quotes • Although single quotes are more commonly used
  • 40. Accessing a string • String can be accessed by index operator and slice operator. (i) Index operator: A string is a sequence operator. A character in the string can be accessed through the index operator Syntax: stringname[index] Example: >>> s=“ program” >>>s[2] -- o >>>s[6] -- m >>> s[0] -- p >>> s[7] -- Out of range
  • 41. • 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] ---
  • 42. 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
  • 43. 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
  • 44. 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
  • 45. • lower() ---- Converts a string into lower case >>> s=“KNCET” >>> s.lower() ---- kncet • upper() ---- Converts a string into upper case >>>s=“kncet” >>>s.upper() ---- KNCET • swapcase() ---- lowercase becomes upper case and vice versa >>> s=“knceT” >>> s.swapcase() ---- KNCEt • replace(old,new) ---- Returns a string where a specified value is replaced with a specified value >>>s=“hai hello” >>>s.replace(“hai”,”kncet”) ---- kncet hello
  • 46. 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
  • 47. • isspace() --- Returns true if this contains only whitespace characters >>> a=“ “ >>> a.isspace() --- True • isupper() --Returns true if all characters in the string are upper case >>> a=“welcome” >>> a.isupper() ---- False
  • 48. Comparing Strings • You can compare strings by using the comparison operators (==, !=,>,=>,=<,<) • Python compares strings by comparing their corresponding characters. • It does this by evaluating the characters numeric code • Small letters starts from 97 • Uppercase Letters from 65 Example: >>> a=“KNCET” >>> b=“kncet” >>> a= =b ---- False
  • 49. Iterating a String • A string is iterable. This means that you can use a for loop to traverse all characters in the string sequentially Example: >>> s="kncet" >>> for i in s: print(i) ---- k n c e t
  • 50. 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
  • 51. Basic program in class and objects Class parent: def fun1(self): print(“This is function1”) Class Child(): def fun2(self) print(“this is function 2”) Obj=parent() Obj.fun1() Obj=child() Obj.fun2()
  • 52. Inheritance concept…… Class parent: def fun1(self): print(“This is function1”) Class Child(parent): def fun2(self) print(“this is function 2”) Obj=child() Obj.fun1() Obj.fun2()
  • 53. 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. Base class Derived Class Extends
  • 54. Super classes • The class from which a class inherits is called the super class • It is also known as parent class or base class. • Superclasses are sometimes called ancestors as well Syntax: class super_class_name: Attributes Methods
  • 55. Subclasses • A class which inherits from a super class is called a subclass. • It is also known as child class. • The child class acquires the properties and can access all the data members and functions defined in the parent class. • Syntax: class derived-class(base class): <class-suite> To create a class that inherits the functionality from another class, send the parent class as a parameter when creating the child class
  • 56. Single Level inheritance: When a child class inherits only a single parent class.
  • 57. Example Example: Class Addition: Def add (self): A=int(input(“Enter the value of :”)) B=int(input(“Enter the value of :”)) C=a+b Print(“addition:”,c) Class Subtraction(Addition): Def sub(self): A=int(input(“Enter the value of :”)) B=int(input(“Enter the value of :”)) C=a-b Print(“addition:”,c) Obj=subtraction() Obj.add() Obj.sub()
  • 58. Multiple Inheritance: When a child class inherits from more than one parent class. Parent 1 Parent 2 Parent 3 Child
  • 59. Example: Class Addition: Def add (self): A=int(input(“Enter the value of :”)) B=int(input(“Enter the value of :”)) C=a+b Print(“addition:”,c) Class Subtraction(Addition): Def sub(self): A=int(input(“Enter the value of :”)) B=int(input(“Enter the value of :”)) C=a-b Print(“addition:”,c) Class Input(Addition,Subtraction): Def base(Self): self.add() self.sub() Obj=Input() Obj.base()
  • 60. Multilevel Inheritance • When a child class becomes a parent class for another child class. Parent 1 Child 1 Child 2
  • 61. Example: Class Addition: Def add (self): A=int(input(“Enter the value of :”)) B=int(input(“Enter the value of :”)) C=a+b Print(“addition:”,c) Class Subtraction(Addition): Def sub(self): A=int(input(“Enter the value of :”)) B=int(input(“Enter the value of :”)) C=a-b Print(“addition:”,c) Class calfun(Subtraction): Def call(Self): self.add() self.sub() Obj=calfun() Obj.call()
  • 62. 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.
  • 63.
  • 64. Example: 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()
  • 65. 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.
  • 66. 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)
  • 67. Example Class ram: def project(self): Print(“online shopping management system”) Class sam(ram): def project(self): super().project() Print(“online voting system”) Obj=sam() Obj.project()
  • 68. 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.
  • 69. 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)
  • 70. Similarly, for string data types, + operator is used to perform concatenation. Example: str1 = "Python" str2 = "Programming" print(str1+" "+str2) output: Python Programming This is one of the most simple occurrences of polymorphism in Python.
  • 71. Here are some functions in Python which are compatible to run with multiple data types. One such function is the len() function. It can run with many data types in Python. Example: print(len("Programiz")) print(len(["Python", "Java", "C"])) print(len({"Name": "John", "Address": "Nepal"}))
  • 72. Polymorphism and dynamic Binding: We can use the concept of polymorphism while creating class methods as Python allows different classes to have methods with the same name. Polymorphism means that an object of a subclass can be passed to a parameter of a super class type. A method may be implemented in several classes along the inheritance chain. is also called method overriding. Python decides which method is invoked at runtime. This is known as dynamic binding.
  • 73. Example: class India(): def capital(self): print("New Delhi is the capital of India.") def language(self): print("Hindi is the most widely spoken language of India.") def type(self): print("India is a developing country.")
  • 74. 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()
  • 75. 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.
  • 76. 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()
  • 77. 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. Syntax: Isinstanec(object,type)
  • 78. Example: class myObj: name = "John" y = myObj() x = isinstance(y, myObj)
  • 79. Class Relationship: To design classes, you need to explore the relationships among classes. The common relationships among classes are association, aggregation, composition, and inheritance.
  • 80. 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
  • 81. 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.
  • 82. 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):
  • 84. 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.
  • 85. • 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.
  • 86. 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.