Unit 5
Unit 5
Introduction
1. Class: Classes are defined by the user. The class provides the basic structure for an object.
It consists of data members and method members that are used by the instances, (objects)
of the class.
2. Object: A unique instance of a data structure that is defined by its class. An object
comprises both data members (class variables and instance variables) and methods, Class
itself does nothing but the real functionality is achieved through their objects. Object is an
instance or occurrence of the class, It takes the properties (variables) and uses the behavior
(methods) defined in the class.
3. Data Member: A variable defined in either a class or an object; it holds the data
associated with the class or object.
4. Instance Variable: A variable that is defined in a method; it scope is only within the
object that defines it.
5. Class Variable: A variable that is defined in the class and can be used by all the instances
of that class.
6. Instance: An object is an instance of the class,
7. Instantiation: The process of creation of an object of a class,
8. Method: methods are the functions that are defined in the definition of class and are
used by various instances of the class.
9. Function Overloading: A function defined more than one time with different
behavior's is known as function overloading_ The operation performed varies by the
types of objects or arguments involved.
10. Encapsulation: Encapsulation is the process of binding together the methods and
data variables as a single entity of class. This keeps both the data and functionality
code safe from the outside world. It hides the data within the class and makes it
available only through the methods.
11. Inheritance: The transfer of the characteristics of a class to other classes that are
derived from it. A class “A” that can use the characteristics of another class ”B” is
Object oriented programming in Python Unit 5
said to be derived class i.e. a class inherited from B. This process is called
inheritance.
12. Polymorphism: Polymorphism allows one interface to be used for a set of actions
i.e., one name may refer to different functionality. The word polymorphism means
having many forms. In programming, polymorphism means same function name (but
different signatures) being uses for different types.
13. Data Abstraction: The basic idea of data abstraction is to visible only the necessary
information, unnecessary information will be hidden from the outside world.
Abstraction is a process of hiding the implementation details and showing only
functionality to the user. Another way, it shows only essential things to the user and
hides the internal details, for example, sending SMS where we type the text and send
the message. We don't know the internal processing about the message delivery.
CLASSES
● Python is an object oriented programming language. Almost everything in Python is an
object, with its properties and methods.
● Object is simply a collection of data (variables) and methods (functions) that act on those
data.
● A class is like an object constructor or a "blueprint" for creating objects. A class defines
the properties and behavior (variables and methods) that is shared by all its objects.
Creating Classes
● A class is a block of statements that combine data and operations, which are performed on
the data, into a group as a single unit and acts a blueprint for the creation of objects.
● To create a class, use the keyword 'class', Here's the very basic structure of python class
definition.
syntax:
class className:
'Optional class documentation string'
list of python class variables
# python class constructor
# python class method definitions
class car:
pass
Here, the pass statement is used to indicate that this class is empty.
Object oriented programming in Python Unit 5
● In a class we can define variables, functions, etc.While writing any function in class we
have to pass at least one argument that is called self Parameter.
● The self parameter is a reference to the class itself and is used to access variables that
belongs to the class. It does not have to be named self, we can call it whatever we like, but it
has to be the first parameter of any function in the class
●
>>>class student:
def display(self): # defining method in class
print("Hello Python')
● In Python programming self is a default variable that contains the memory address of the
instance of the current class.So we can use self to refer to all the instance variables and
instance methods.
obj_name=class_name()
Example:
sl=student()
sl.display()
Object oriented programming in Python Unit 5
● complete program with class and objects on interactive interpreter is given
below:
● >>> class student:
def display(self):#a defining method in class
print(“hello Python”)
Hello Python
● Complete program with class and objects on interactive interpreter in .py file is given below:
class student:
def display(self):
print("Hello Python')
sl=student()
s1=display()
Output:
Hello Python
class Car:
def get(self, color, style):
self .color = color
self. style = style
def put(self):
print(self.color)
print(self.style)
c = Car()
c.get("Sedan", "Black")
c.put()
Output:
Sedan
Black
Class variable is defined in the class and can be used by all the instances of that class. Class
attribute is same for all objects, and there's only one copy of that variable that is shared with all
objects. Any changes made to that variable will reflect in all other objects.
Instance variables are unique for each instance, while class variables are shared by alI
instances.
class Sample:
x=2 # x is class variable
def get(self, y): # y is instance variable
self.y = y
s=Sample()
s.get(3) # Access attributes
print(s.x," ",s.y)
s2 = Sample()
s2.y=4 # Modify attribute
print(s2.x," ",s2.y)
Output:
23
24
DATA HIDING
Data hiding is a software development technique specifically used in Object-Oriented
Programming (OOP) to hide internal object details (data members).
Data hiding ensures exclusive data access to class members and protects object integrity by
preventing unintended or intended changes.
Data hiding is also known as information hiding. An object's attributes may or may not be
visible outside the class definition.
Object oriented programming in Python Unit 5
We need to name attributes with a double underscore (_) prefix, and those attributes then are
not be directly visible to outsiders. Any variable prefix with double underscore is called private
variable which is accessible only with class where it is declared.
Example: For data hiding.
class Counter:
__secretCount = 0 #private variable
def count(self): #public method
self.__secretCount += 1
print ("count=”,self.__secretCount) # accessible in the $sameclass
cl= Counter()
cl.count() #invoke method
cl.count()
print ("Total count=",c1.__secretCount) #cannot access private variable directly
output:
count= 1
count= 2
Traceback (most recent call last):
File "<string>", line 9, in <module>
NameError: name 'c1' is not defined
>
Types Description
Public methods Accessible from anywhere i.e. inside the class in which they
are defined, in the sub class, in the same script file as well
Private methods Accessible only in their own class. Starts with two underscores.
Private variables Accessible only in their own class or by a method if defined. Starts with two
underscores.
Output
Object oriented programming in Python Unit 5
b= 21
public method is called
a=10
Constructor:
A constructor is a special method i.e., is used to initialize the instance variable of a class.
Creating Constructor in Class:
● A constructor is a special type of method (function) which is used to initialize the
instance members of the class.
● Constructors are generally used for instantiating an object. The task of constructors is
to initialize (assign values) to the data members of the class when an object of class is
created.
● Python class constructor is the first piece of code to be executed when we create a new
object of a class.
● In Python the _ _init_ _() method is called the constructor and is always called when an
object is created.
● Primarily, the constructor can be used to put values in the member variables. We may
also print messages in the constructor to be confirmed whether the object has been
created.
Syntax:
def _ _init_ _(self):
# body of the constructor
_ ________init is a special method in Python classes, which is the constructor method for a
class. In the following example you can see how to use it.
Example 1: For creating constructor.
class Person:
def __init__(self, rollno,name,age):
self.rollno=rollno
self.name= name
self.age = age
print("Student object is created")
p=Person(11,"rudra”, 7)
print("Rollno of student. ", p.rollno)
print("name of student- ",p.name)
print("Age of student- ",p.age)
Output:
Student object is created
Rollno of student. 11
Object oriented programming in Python Unit 5
Mame of student- rudra
Age of student- 7
Example 2: Define a class named Rectangle which can be constructed by a length and
width. The Rectangle class has a method which can compute the area.
class Rectangle:
def __init__(self,l,w):
self.length = l
self.width =w
def area(self):
return self.length*self.width
r = Rectangle(2,10)
print(r.area())
Output:
20
Example 3: Create a Circle class and initialize it with radius. Make two methods getArea
and geteircumference inside this class.
class Circle():
def __init__(self,radius):
self.radius = radius
def getArea(self):
return 3.14*self.radius*self.radius
def getCircumference(self):
return self.radius*2*3.14
c=Circle(5)
print("Area",c.getArea())
print("Circumference",c.getCircumference())
Output:
Area 78.5
Circumference 31.400000000000002
The types of constructors
1.Default Constructor.
The default constructor is simple constructor which does not accept any arguments. It's
definition. has only one argument which is a reference to the instance being constructed.
Object oriented programming in Python Unit 5
Example 1: Display Hello message using default constructor.
class Student:
def __init__(self):
print("This is default constructor")
def show(self,name):
print("Hello",name)
s1=Student()
s1.show("rudra")
Output
This is default constructor Hello rudra
Example 2: Counting the number of objects of a class.
class Student:
count=0;
def__init__(self):
Student.count=Student.count + 1
s1=Student()
s2=Student()
print("The number of student objects",Student.count)
Output:
The number of student objects: 2
2. Parameterized Constructor:
output
this is parametrized constructor
Object oriented programming in Python Unit 5
Hello rudra
Destructor
▪ A class can define a special method called a destructor with the help of _ _del_ _. It is invoked
automatically when the instance (object) is about to be destroyed.
Output:
METHOD OVERLOADING
Method overloading is the ability to define the method with the same name but with the different
number of arguments
With this ability one method can perform different tasks, depending on the number of arguments or
the types of the arguments given.
Method overloading is a concept in which a method in a class performs operations according to the
parameters passed to it.
As in other languages we can write a program having two methods aith same name but with
different number of arguments or order of arguments but in python if we will try to do the same we
will get the following issue with method overloading in Python:
# to calculate area of rectangle
def area(length,breadth):
calc = length*breadth
print (calc)
def area(size):
calc=size*size
Object oriented programming in Python Unit 5
print (calc)
area(3)
area(4,5)
output:
9
TypeError: area() takes exactly 1 argument( 2given)
Python does not support method overloading, i.e., it is not possible to define more than one method
with the same name in a class in Python.
This is because method arguments in python do not have a Type. A method accepting one
argument can be called with an integer value, a string or a double as shown in next example.
class Demo:
def method( self, a) :
print (a)
obj= Demo( )
obj.method( 50)
obj.method("rudra")
obj.method (100.2)
Output:
50
rudra
100.2
Same method works for three different data types. Thus, we cannot define two methods
with the same name and same number of arguments but having different type as shown in
the above example. They will be treated as the same method.
it is clear that method overloading is not supported in python but that does not mean
that we cannot call a method with different number of arguments. There are a couple
of alternatives available in python that make it possible to call the same method but
with different number of arguments.
Using Default Arguments:
it is possible to provide default values to method arguments while defining a method. If method
arguments are supplied default values, then it is not mandatory to supply those arguments while
calling method as shown in next example.
class Operation:
def add(self,a,b):
return a+b
op1=Operation()
# To add two integer numbers
print( "Addition of integer numbers-",op1.add(10,20))
#To add two floting point numbers
print("Addition of integer numbers=",op1.add(11.12,12.13))
# To add two strings
print("Addition of integer numbers=",op1.add("hello","python"))
Output:
Addition of integer numbers= 30
Addition of integer numbers= 23.25
Addition of integer numbers= HelloPython
Inheritance and composition class
Is a method of inheriting the properties of parent class into a child class is known as inheritance. It
is an OOP concept. Following are the benefits of inheritance.
Object oriented programming in Python Unit 5
1. Code reusability- we do not have to write the same code again and again; we can just inherit
the properties we need in a child class.
2. It represents a real world relationship between parent class and child class.
3. It is transitive in nature. If a child class inherits properties from a parent class, then all other
sub-classes of the child class will also inherit the properties of the parent class.
The inheritance feature allows us to make it possible to use the code of the existing class
by simply creating a new class and inherits the code of the existing class.
Inheritance
In inheritance objects of one class procure the properties of objects of another class.
Inheritance provide code reusability, which means that some of the new features can be
added to the code while using the existing code_ The mechanism of designing or
The new class is called derived class or child class and the class from which this derived
In inheritance, the child class acquires the properties and can access all the data members
and functions defined in the parent class. A child class can also provide its specific
Syntax:
class A:
#properties of class A
Object oriented programming in Python Unit 5
class B(A):
#class B inheriting property of class A
#more properties of class B (Single Inheritance)
Example Inheritance without using constructor.
class Vehicle: #parent class
name="Maruti"
def display(self):
print("Name- ",self.name)
class Category(Vehicle): #derived class
price=2000
def disp_price(self):
print("Price-$",self.price)
car1=Category()
car1.display()
car1.disp_price()
Output:
Name= Maruti
Price-$ 2000
Output:
Name= Maruti
Price-$ 2000
Name= BmW
Price-$ 5000
Object oriented programming in Python Unit 5
Multilevel Inheritance:
Multi-level inheritance is archived when a derived class inherits another derived class.
There is no limit on the number of levels up to which, the multi-level inheritance is
archived in python.
In multilevel inheritance we inherit the classes at multiple separate levels.We have three
classes A, B and C, where A is the super class, B is its sub(child) class and C is the sub class of
B.
Syntax:
class A:
# properties of class A
class B(A):
#class B inheriting property of class A
# more properties of class B
class C(B):
class C inheriting property of class B
# thus, class C also inherits properties of class A
#more properties of class C
Syntax:
class A:
# variable of class A
#functions of class A
class B:
# variable of class A
#functions of class A
class C(A, B):
#class C inheriting property of both classA and B
add more properties to class
Fig. 5.3
Example:
class Father:
def displayl(self):
print("Father")
#The child class Father inherits the base class Grandfather
class Mother:
def display2(self):
print("Mother")
#The child class Son inherits another child class Father
class Son(Father,Mother):
def display3(self):
print("Son")
s=Son()
Object oriented programming in Python Unit 5
s.display3()
s.display2()
s.displayl()
Output:
Son
mother
Father
Hierarchical Inhertance
when more than one derived classes classes are created from the single base — it is called as
hierarchical inheritance.
In following program, we have a parent (base) class name Email and two child (derived) classes
named Gmail and yahoo.
Object oriented programming in Python Unit 5
Example: For hierarchical inhertance
class Email:
def send_email(self, msg):
print()
class Gmail(Email):
def send_email(self, msg):
print(“Sending Gmail”,msg)
class Yahoo(Email):
def send_email(selt,msg):
print("sending yahoo",msg)
clientl = Gmail()
clientl.send_email("hello")
client2 =Yahoo()
client2.send_email("hello")
Output:
Sending Gmail hello
sending yahoo hello
Method Overriding
Overriding is the ability of a class to change the implementation of a method provided by one of its
base class_ Method overriding is thus a strict part of the inheritance mechanism.
To override a method in the base class, we must define a new method with same name and same
overriding is a very important part of ooP since it is the feature that makes inheritance exploit its lull
power. Through method overriding a class may -copy" another class, avoiding duplicated code, and
The functionality of the parent class method is changes by overriding the same method in the child
class. Inheritance is one of the most important concept of OOP. It provides code reusability,
readability and transition of properties which helps in optimized and efficient code building. Python
programming language is loaded with concepts like inheritance. Enormous python applications call
output:
This is derived class-
Output:
This is base class.
This is derived class.
Object oriented programming in Python Unit 5
Composition Classes
● In composition, we do not inherit from the base class but establish relationships between
classes through the use of instance variables that are references to other objects.
● Composition also reflects the relationships between parts, called a "has-a- relationships. Some
GOP design texts refer to composition as aggregation.
● It enables creating complex types by combining objects of other types. This means that a class
Composite can contain an object of another class Component.
● UML represents composition as shown in Fig
The composite side can express the cardinality of the relationship. The cardinality
indicates the number or valid range of Component instances the Composite class will
contain. Cardinality can be expressed in the following ways:
A number indicates the number of Component instances that are contained in the
Composite. The symbol indicates that the Composite class can contain a variable
number of Component instances.
A range 1.4 indicates that the Composite class can contain a range of Component
instances_ The range is indicated with the minimum and maximum number of
instance, or minimum and many instances like in 1.*.
Syntax:
Class GenericClass:
define some attributes and methods
class ASpecificClass:
Instance variable of_generic class=GenericClass
#use this instance somewhere in the class
some method(Instance variable of_generic class)
In following program, we have three classes Email, Gmail and yahoo. In email class we are
referring the Gmail and using the concept of Composition.
Example: For composition.
class Gmail:
def send_email(self, msg):
print("Sending from gmail",msg)
class Yahoo:
Object oriented programming in Python Unit 5
def send_email(self, msg):
print( "Sending from Yahoo",msg)
class Email:
provider=Gmail()
def set_provider(self,provider):
self.provider=provider
def send_email(self, msg):
self.provider.send_email(msg)
clientl = Email()
clientl.send_email("Hello")
clientl.set_provider(Yahoo())
clientl.send_email("Hello")
Output:
Sending from gmail Hello
Sending from Yahoo Hello
● In Python, every time we use an expression of the form object.attr, (where object is an
instance or class object), Python searches the namespace tree from bottom to top,
beginning with object, looking for the first aril- it can find.
This includes references to self attributes in the methods. Because Lower definitions in the
tree override higher ones, inheritance forms the basis of specialization. Program code in Fig.
below create a tree of objects in memory to be searched by attribute inheritance.
● Calling a class creates a new instance that remembers its class, running a class statement
creates a new class and superclasses are listed in parentheses in the class statement header.
● Each attribute reference triggers a new bottom - up tree search - even references to self
attributes within a class's methods.
Object oriented programming in Python Unit 5
●
● Fig summarizes the way namespace trees are constructed and populated with names. Generally:
1. Instance attributes are generated by assignments to self attributes in methods.
2. Class attributes are created by statements (assignments) in class statements.
3. Superclass links are made by listing classes in parentheses in a class statement header.
The net result is a tree of attribute namespaces that leads from an instance, to the class it
was generated from, to all the superclasses listed in the class header.
Python searches upward in this tree, from instances to superclasses, each time we use
qualification to fetch an attribute name from an instance object.
Specializing Inherited Methods:
● The tree-searching model of inheritance just described turns out to be a great way to specialize
systems. Because inheritance finds names in derived classes before it checks base classes,
derived classes can replace default behavior by redefining their base classes' attributes.
● In fact, we can build entire systems as hierarchies of classes, which are extended by
adding new external derived classes rather than changing existing logic in-place. The
idea of redefining inherited names leads to a variety of specialization techniques.
● For instance, derived classes may replace inherited attributes completely, provide
attributes that a base class expects to find, and extend base class methods by calling
back to the base class from an overridden method. Here is an example that shows how
extension works.
Example For specialized inherited methods.
The derived class replaces base's method function with its own specialized version, but within
the replacement, derived calls back to the version exported by base class to carry out the
default behavior.
In other words, derived class.display0 just extends base class. display() behavior, rather than
replacing it completely.
output:
Inheritor.....
in Super.method
provider---
Replacer.....
in Replacer.method
provider---
Extender.....
in Super.method
in Exteneler.methodprovider---
in Provider action
At the end of this program instances of three different classes are created in a for loop. Because
classes are objects, you can put them in a tuple and create instances generically.
Classes also have the special name attribute, which preset to a string containing the name
in the class header.
In previous example, when we call the delegate method through a provider instance, two
indepanden inheritance searches occur:
1. on the initial x-delegate call. Python finds the delegate method. in Super by searching
the Provider instance and above. 'The instance x is passed into the method's self-
argument as usual.
2. Inside the super.delegate method, self.action invoices a new independent inheritance
search of self and above. Because self-references a Provider instance the action method
is located in the Provider subclass.
The Super class in this example is what is sometimes called an abstract super class a class that
expects parts of its behavior to be provided by its subclasses.
● Single Inheritance
When a child class inherits only a single parent class.
Object oriented programming in Python Unit 5
class Parent:
def func1(self):
print ("this is function one")
class Child(Parent):
def func2(self):
print (" this is function 2 ")
ob = Child ()
ob. func1()
ob. func2()
● Multiple Inheritance
When a child class inherits from more than one parent class.
class Parent:
def func1(self):
print ("this is function 1")
class Parent2:
def func2(self):
print ("this is function 2")
class Child (Parent, Parent2):
def func3(self):
print ("this is function 3")
ob = Child ()
ob. func1()
ob. func2()
ob. func3()
● Multilevel Inheritance
When a child class becomes a parent class for another child class.
class Parent:
def func1(self):
print ("this is function 1")
class Child(Parent):
def func2(self):
print ("this is function 2")
class Child2(Child):
def func3("this is function 3")
ob = Child2()
ob. func1()
ob. func2()
ob. func3()
Object oriented programming in Python Unit 5
● Hierarchical Inheritance
Hierarchical inheritance involves multiple inheritance from the same base or parent class.
class Parent:
def func1(self):
print ("this is function 1")
class Child(Parent):
def func2(self):
print ("this is function 2")
class Child2(Parent):
def func3(self):
print ("this is function 3")
ob = Child ()
ob1 = Child2()
ob. func1()
ob. func2()
● Hybrid Inheritance
Hybrid inheritance involves multiple inheritance taking place in a single program.
class Parent:
def func1(self):
print ("this is function one")
class Child(Parent):
def func2(self):
print ("this is function 2")
class Child1(Parent):
def func3(self):
print (" this is function 3"):
class Child3(Parent, Child1):
def func4(self):
print (" this is function 4")
ob = Child3()
ob. func1()
ob = Child ()
ob. func2()
class Child(Parent):
def func1(self):
print ("this is child function")
ob = Child ()
ob. func1()