0% found this document useful (0 votes)
13 views13 pages

PWP Unit 5

The document provides a comprehensive overview of Object Oriented Programming (OOP) concepts in Python, including classes, objects, method overloading, overriding, inheritance, and data encapsulation. It explains key principles such as data hiding, abstraction, and various types of inheritance, along with examples to illustrate each concept. Additionally, it discusses the use of the super() method and composition in OOP design.

Uploaded by

preetibhoge212
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views13 pages

PWP Unit 5

The document provides a comprehensive overview of Object Oriented Programming (OOP) concepts in Python, including classes, objects, method overloading, overriding, inheritance, and data encapsulation. It explains key principles such as data hiding, abstraction, and various types of inheritance, along with examples to illustrate each concept. Additionally, it discusses the use of the super() method and composition in OOP design.

Uploaded by

preetibhoge212
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

UNIT V

Object Oriented Programming in Python

❖ Creaing Classes and Objects :

o Classes :
▪ Python is an object oriented programming language.
▪ Almost everything in Python is an object, with its properties and
methods.
▪ Class is a collection of attributes and methods.
▪ A Class is like an object constructor, or a "blueprint" for creating
objects.

▪ Syntax:
Class Class_name : #here we created empty class.
Pass
▪ Example :
Class Rectangle :

o Objects :
▪ Object is an instance of class.
▪ Objects are used to access the attributes and methods of the class.

▪ Syntax:
Object name=class name ( )

▪ Example :
Rect = Rectangle()

o init method :
▪ Python supports very unique method named as init () method.
▪ This method gets executed when instance of a class gets created.
▪ It is also called as initialize method as constructor in oop.
▪ Use the init () function to assign values to object properties, or
other operations that are necessary to do when the object is being
created

▪ Example :

Class Rectangle:
def init (self):
self.lengt=10
self.width=12
def rectangle_area(self):
return self.length*self.width
Rect=Rectangle()
Print(“thearea of rectangle is :”,Rect.rectangle_area)

❖ Method Overloading :
o Method overloading is the ability to define the method with the same
name but with a different number of arguments and data types.
o With this ability one method can perform different tasks, depending on
the number of arguments or the types of the arguments given.
o Method overloading is a concept in which a method in a class performs
operations according to the parameters passed to it.

Example: With a method to perform different operations using method


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

o Python does not support method overloading, that is, it is not possible to
define more than one method with the same name in a class in Python.
o 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('Meenakshi')
obj.method(100.2)
Output:
50
Meenakshi
100.2

❖ Method Overriding :
o Method overloading is the ability to define the method with the same
name and same number of arguments and data types.
o Method overriding is an ability of a class to change the implementation of
a method provided by one of its base class.
o Method overriding is thus a strict part of inheritance mechanism.
o To override a method in base class, we must define a new method with
sam name and same parameters in the derived class.
o Overriding is a very important part of OOP since it is feature that makes
inheritance exploit its full power.
o 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

class A:
def display(self):
print("This is base class")
class B(A):
def display(self):
print("This is derived class")
obj=B() # instance of child
obj.display() # child class overriden method

Output :
This is derived class

❖ Using super() Method:

o The super() method gives you access to methods in a super class from
the subclass that inherits from it.
oThe super() method returns a temporary object of the superclass that then
allows you to call that superclass’s method.

oExample: For method overriding with super()


class A:
def display(self):
print("This is base class")
class B(A):
def display(self):
super().display()
print("This is derived class")
obj=B() # instance of child
obj.display() # child class overriden method

Output :
This is base class
This is derived class

❖ Data Hiding :

o Data hiding is a software development technique specifically used in


object oriented programming to hide internal object details(data
members).
o It ensures exclusive data access to class members and protects object
integrity by preventing unintended or intended changes.
o Data hiding is also known as information hiding. An objects attributes
may or may not be visible outside the class definition.
o We need to name attributes with a double underscore(_ _) prefix and
those attributes the are not directly visible to outsiders. Any variable
prefix with double underscore is called private variable which is
accessible only with class where it is declared.
o To access public member we can access directly through the object
name.
o Acceding public members inside and outside both are possible.

Example :

class student:
def init (self):
self.rollno=1 # public variable
self. name="ABC" # private variable
S1=student()
print(S1.rollno)
print(S1. name)
o after execution of above code you will get a error , ‘student’ object
has no attribute “ name”. So we cannot access private members
outside the class, we have to used those members inside the class.

Class student:
def init (self):
self.rollno=1 # public variable
self. name="AB # private variable
def display(self):
print(self.rollno)
print(self. name)
S1=student()
S1.display()

❖ Data Abstraction :

o We can restrict access of methods and variables in a class with the help
of encapsulation. It will prevent the data being modified by accident.
o Encapsulation is used to hide the value or state of a structured data
object inside a class, preventing unauthorized parties direct access to
them.
o Data abstraction refers to providing only essential information about the
data to the outside world, hiding the background details of
implementation.
o Encapsulation is a process to bind data and functions together into a
single unit i.e. class while abstraction is a process in which the data
inside the class is the hidden from outside world.
o In short hiding internal details and showing functionality is known as
abstraction.
o To support encapsulation, declare the methods or variables as private in
the class. The private methods cannot be called by the object directly. It
can be called only from within the class in which they are defined.
o Any function with double underscore is called private method.
Access modifiers for variables and methods are:
oPublic methods / variables- Accessible from anywhere inside the class,
in the sub class, in same script file as well as outside the script file.
oPrivate methods / variables- Accessible only in their own class. Starts
with two underscores.
Example: For access modifiers with data abstraction

class student:
a=10 #private variable
b=20 #public variable
def private_method(self): #private method
print("Private method is called")
def public_method(self): #public method
print("public method is called")
print("a= ",self. a) #can be accessible in same class
s1=student()
# print("a= ",s1. a) #generate error
print("b=",s1.b)
# s1. private_method() #generate error
s1.public_method()

Output:
b= 20
public method is called
a= 10

❖ Inheritance :

o The mechanism of designing and constructing classes from other classes is


called inheritance.
o Inheritance is the capability of one class to derive or inherit the properties
from some another class.
o 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.
The benefits of inheritance are:

1. It represents real-world relationships well.


2. It provides reusability of a code. We don’t have to write the same code
again and again. Also, it allows us to add more features to a class without
modifying it.
3. It is transitive in nature, which means that if class B inherits from another
class A, then all the subclasses of B would automatically inherit from class
A.
Example 1:

class Parent1:
def func_1(self):
print ("This function is defined inside the parent class.")

# now, we will create the Derived class


class Child1(Parent1):
def func_2(self):
print ("This function is defined inside the child class.")

# Driver's code
object = Child1()
object.func_1()
object.func_2()

Output :
This function is defined inside the parent class.
This function is defined inside the child class.

Example 2:
class vehicle: #parent class name="Maruti"
def display(self):
print("Name= ",self.name)
class category(vehicle): # drived class
price=400000
def disp_price(self):
print("price= ",self.price)
car1=category()
car1.display()
car1.disp_price()
Output:

Name= Maruti
price= 400000

❖ Multilevel Inheritance :
In multilevel inheritance, features of the base class and the derived class are further
inherited into the new derived class. This is similar to a relationship representing a
child and grandfather.

Example :

class Mother1:
mothername1 = " "
def mother1(self):
print(self.mothername1)

# Here, we will create the Base class 2


class Father1:
fathername1 = " "
def father1(self):
print(self.fathername1)

# now, we will create the Derived class


class Son1(Mother1, Father1):
def parents1(self):
print ("Father name is :", self.fathername1)
print ("Mother name is :", self.mothername1)

# Driver's code
s1 = Son1()
s1.fathername1 = "Rajesh"
s1.mothername1 = "Shreya"
s1.parents1()

Output :

Father name is : Rajesh


Mother name is : Shreya

❖ Multilevel inheritance :

o Multilevel inheritance, the features that are part of the original class, as well
as the class that is derived from it, are passed on to the new class. It is
similar to a relationship involving grandparents and children.

# Here, we will create the Base class


class Grandfather1:

def init (self, grandfathername1):


self.grandfathername1 = grandfathername1

# here, we will create the Intermediate class


class Father1(Grandfather1):
def init (self, fathername1, grandfathername1):
self.fathername1 = fathername1

# here, we will invoke the constructor of Grandfather class


Grandfather1. init (self, grandfathername1)

# here, we will create the Derived class


class Son1(Father1):
def init (self,sonname1, fathername1, grandfathername1):
self.sonname1 = sonname1
# here, we will invoke the constructor of Father class
Father1. init (self, fathername1, grandfathername1)

def print_name(self):
print('Grandfather name is :', self.grandfathername1)
print("Father name is :", self.fathername1)
print("Son name is :", self.sonname1)

# Driver code
s1 = Son1('John', 'John Jr', 'John Jr Jr')
print (s1.grandfathername1)
s1.print_name()

Output :
John Jr Jr
Grandfather name is : John Jr Jr
Father name is : John Jr
Son name is : John

❖ Hierarchical Inheritance :

o Hierarchical Inheritance If multiple derived classes are created from the


same base, this kind of Inheritance is known as hierarchical inheritance. In
this instance, we have two base classes as a parent (base) class as well as
two children (derived) classes.
Example :
# Python program for demonstrating Hierarchical inheritance

# Here, we will create the Base class


class Parent1:
def func_1(self):
print ("This function is defined inside the parent class.")

# Derived class1
class Child_1(Parent1):
def func_2(self):
print ("This function is defined inside the child 1.")

# Derivied class2
class Child_2(Parent1):
def func_3(self):
print ("This function is defined inside the child 2.")

# Driver's code
object1 = Child_1()
object2 = Child_2()
object1.func_1()
object1.func_2()
object2.func_1()
object2.func_3()

Output :
This function is defined inside the parent class.
This function is defined inside the child 1.
This function is defined inside the parent class.
This function is defined inside the child 2.

❖ Composition classes :

o In composition we do not inherit from the base class but establish


relationship between classes through the use of instance variables that are
references to other objects.
o Composition means that an object knows another object and explicitly
delegates some tasks to it. While inheritance is implicit, composition is
explicit in python.
o We use composition when we want to use some aspects of another class
without promising all of the features of that other class.
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_varable_of_generic_class)

o For example, we have three classes email, gmail and yahoo. In email
class we are referring the gmail and using the concept of composition.

class gmail:
def send_email(self,msg):
print("sending '{}' from gmail".format(msg))
class yahoo:
def send_email(self,msg):
print("sending '{}' from yahoo".format(msg))
class email:
provider=gmail()
def set_provider(self,provider):
self.provider=provider
def send_email(self,msg):
self.provider.send_email(msg)
client1=email()
client1.send_email("Hello")
client1.set_provider(yahoo())
client1.send_email("Hello")

Output:
sending 'Hello' from gmail
sending 'Hello' from yahoo

❖ Customization via Inheritance specializing inherited methods:

o The tree-searching model of inheritance turns out to be a great way to


specialize systems. Because inheritance finds names in subclasses before
it checks superclasses, subclasses can replace default behavior by
redefining the superclass's attributes.
o In fact, you can build entire systems as hierarchies of classes, which are
extended by adding new external subclasses rather than changing existing
logic in place.
o The idea of redefining inherited names leads to a variety of specialization
techniques.
o For instance, subclasses may replace inherited attributes completely,
provide attributes that a superclass expects to find, and extend superclass
methods by calling back to the superclass from an overridden method.
o Example- For specilaized inherited methods
class A:
"parent class" #parent class
def display(self):
print("This is base class")
class B(A):
"Child class" #derived class
def display(self):
A.display(self)
print("This is derived class")
obj=B() #instance of child
obj.display() #child calls overridden method

Output :
This is derived class
This is base class

o In the above example derived class.display() just extends base


class.display() behavior rather than replacing it completely.
o Extension is the only way to interface with a superclass.

You might also like