Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unit3py 240928091622 0ea1eac8

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 82

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.
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’s Clients use the
Contract class through
Class
(headers of the class’s
initializer and contract
methods

Class abstraction separates class implementation


from the use of the class.
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”)
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)
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

• 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
Single Level inheritance:
When a child class inherits only a single parent class.
Example:
class parent:
def add(self):
print(“addition”)
class child (parent):
def sub(self):
print(“subtraction”)
a=parent()
a.add()
a.sub()
Multiple Inheritance:
When a child class inherits from more than
one parent class.

Parent 1 Parent 2 Parent 3

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

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.
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.

You might also like