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.
Object oriented programming in Python Unit 5
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 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
Object oriented programming in Python Unit 5
class Car:
pass
Here, the pass statement is used to indicate that this class is empty.
● 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
● We can write a class on interactive interpreter or in a..py file
>>>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.
Syntax
obj_name=class_name()
Example:
Object oriented programming in Python Unit 5
sl=student()
sl.display()
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
Instance and class variables
Object oriented programming in Python Unit 5
Instance variable is defined in a method and its scope is only within the object that
defines it. Instance attribute is unique to each object (instance). Every object of that class
has its own copy of that variable. Any changes made to the variable don't reflect in other
objects of that class.
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.
Following example demonstrates the use of instance and class variable.
Example: For instance and class variables.
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.
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
Object oriented programming in Python Unit 5
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
Object oriented programming in Python Unit 5
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
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:
Object oriented programming in Python Unit 5
Output:
Student object is created
Rollno of student. 11
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.
Object oriented programming in Python Unit 5
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 includes
1.default constructor and
2.parameterized constructor.
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.
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")
Object oriented programming in Python Unit 5
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:
● Constructor with parameters is known as parameterized constructor.
● The parameterized constructor take its first argument as a reference to the instance being
constructed known as self and the rest of the arguments are provided by the programmer.
output
this is parametrized constructor
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:
Output:
None
Test
__main__
(<class 'object'>,)
{'__module__': '__main__', '__init__': <function Test.__init__ at 0x7f9a27e77e50>,
'__dict__': <attribute '__dict__' of 'Test' objects>, '__weakref__': <attribute '__weakref__' of
'Test' objects>, '__doc__': None}
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
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) :
Object oriented programming in Python Unit 5
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
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
constructing classes from other classes is called inheritance.
The new class is called derived class or child class and the class from which this
derived class has been inherited is the base class or parent class.
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 implementation to the functions of the parent class.
Syntax:
class A:
#properties of class A
class B(A):
Object oriented programming in Python Unit 5
#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
Output:
Son
Object oriented programming in Python Unit 5
Father
Grand Father
Multiple Inheritance:
Python provides us the flexibility to inherit multiple base classes in the child class.
Multiple Inheritance means that we are inheriting the property of multiple classes
into one. In case we have two classes, say A and B, and we want to create a new
class which inherits the properties of both A and B.
So it just like a child inherits characteristics from both mother and father, in python,
we can inherit multiple classes in a single child class.
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()
s.display3()
s.display2()
s.displayl()
Object oriented programming in Python Unit 5
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.
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
parameters in the derived class.
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
at the same time enhance or customize part of it.
Example For method overriding.
output:
This is derived class-
Object oriented programming in Python Unit 5
Output:
This is base class.
This is derived class.
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
Object oriented programming in Python Unit 5
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:
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
Object oriented programming in Python Unit 5
● 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.
● 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.
Object oriented programming in Python Unit 5
● 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:
Object oriented programming in Python Unit 5
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.