0% found this document useful (0 votes)
12 views

Unit 2 Final

This document covers fundamental concepts of object-oriented programming in Python, including classes, objects, constructors, polymorphism, encapsulation, inheritance, data abstraction, method overloading, and method overriding. It provides examples for creating classes and objects, implementing methods, and utilizing built-in class functions. Additionally, it explains the differences between method overloading and overriding, and the importance of constructors in initializing class objects.
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)
12 views

Unit 2 Final

This document covers fundamental concepts of object-oriented programming in Python, including classes, objects, constructors, polymorphism, encapsulation, inheritance, data abstraction, method overloading, and method overriding. It provides examples for creating classes and objects, implementing methods, and utilizing built-in class functions. Additionally, it explains the differences between method overloading and overriding, and the importance of constructors in initializing class objects.
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/ 75

UNIT 2 OBJECT ORIENTED CONCEPTS

Class – Objects – Constructors –Polymorphism – Encapsulation -


Inheritance -Data Abstraction- Method Overloading-Method
overriding-Database Access-Data Hiding-Import Class
➢ Execute concepts on Polymorphism, Encapsulation.
➢ Implement Data Abstraction and Inheritance.
➢ Differentiate Method Overloading and Overriding.
➢ Create a class called "Person" with attributes "name" and "age." Make the "age"
attribute private and implement a getter method to access it.
➢ Create a module called "math_operations.py" with a class called "Calculator.“ Import
the "Calculator" class into another script and use its methods to perform mathematical
operations.

2/20/2025 K.ABINAYA Assistant Professor Sbu 1


Python is a versatile programming language that supports various programming
styles, including object-oriented programming (OOP) through the use
of objects and classes.
Python Classes
➢ A class is considered as a blueprint of objects. We can think of the 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.
➢ Consider an example, let’s say you wanted to track the number of dogs that may
have different attributes like breed, age. If a list is used, the first element could be the
dog’s breed while the second element could represent its age.
➢ Let’s suppose there are 100 different dogs, then how would you know which element
is supposed to be which? What if you wanted to add other properties to these dogs?
This lacks organization and it’s the exact need for classes.

2/20/2025 K.ABINAYA Assistant Professor Sbu 2


Define Python Class
We use the class keyword to create a class in Python. For example,

Here,
➢ Bike - the name of the class
➢ name/gear - variables inside the class with default values "" and 0 respectively.
➢ The variables inside a class are called attributes
Some points on Python class:
•Classes are created by keyword class.
•Attributes are the variables that belong to a class.
•Attributes are always public and can be accessed using the dot (.) operator. Eg.:
Myclass.Myattribute
2/20/2025 K.ABINAYA Assistant Professor Sbu 3
Python Objects
➢ An object is called an instance of a class. For example, suppose Bike is a class then
we can create objects like bike1, bike2, etc from the class.
➢ Here's the syntax to create an object.

➢ Here, bike1 is the object of the class. Now, we can use this object to access the class
attributes.
2/20/2025 K.ABINAYA Assistant Professor Sbu 4
Access Class Attributes Using Objects
➢ We use the . notation to access the attributes of a class. For example,

➢ Here, we have used bike1.name and bike1.gear to change and access the value of
name and gear attribute respectively.

2/20/2025 K.ABINAYA Assistant Professor Sbu 5


Example 1: Python Class and Objects

2/20/2025 K.ABINAYA Assistant Professor Sbu 6


Create Multiple Objects of Python Class

2/20/2025 K.ABINAYA Assistant Professor Sbu 7


➢ An object is any entity that has attributes and behaviors. For example, a parrot is an
object. It has
attributes - name, age, color, etc.
behavior - dancing, singing, etc.
Similarly, a class is a blueprint for that object.

2/20/2025 K.ABINAYA Assistant Professor Sbu 8


➢ In the above example, we created a class with the name Parrot with two attributes:
name and age.
➢ Then, we create instances of the Parrot class. Here, parrot1 and parrot2 are
references (value) to our new objects.
➢ We then accessed and assigned different values to the instance attributes using the
objects name and the . notation.

2/20/2025 K.ABINAYA Assistant Professor Sbu 9


Python Methods
We can also define a function inside a Python class. A Python Function defined inside a
class is called a method.
Python Functions
A function is a block of code that performs a specific task.
Suppose, you need to create a program to create a circle and color it. You can create two
functions to solve this problem:
➢ create a circle function
➢ create a color function
Dividing a complex problem into smaller chunks makes our program easy to understand
and reuse.

2/20/2025 K.ABINAYA Assistant Professor Sbu 10


There are two types of function in Python programming:
Types of function

➢ Standard library functions - These are built-in functions in Python that are available to use.
➢ User-defined functions - We can create our own functions based on our requirements.
Python Function Declaration

Here,
def - keyword used to declare a function
function_name - any name given to the function
arguments - any value passed to function
return (optional) - returns value from a function
2/20/2025 K.ABINAYA Assistant Professor Sbu 11
Example: Python Function

Working of Python Function

2/20/2025 K.ABINAYA Assistant Professor Sbu 12


Python Function Arguments
As mentioned earlier, a function can also have arguments. An argument is a value that is
accepted by a function. For example,

If we create a function with arguments, we need to pass the corresponding values while
calling them. For example,

2/20/2025 K.ABINAYA Assistant Professor Sbu 13


Here, add_numbers(5, 4) specifies that arguments num1 and num2 will get values 5 and 4
respectively.
Example 1: Python Function Arguments

2/20/2025 K.ABINAYA Assistant Professor Sbu 14


The return Statement in Python
A Python function may or may not return a value. If we want our function to
return some value to a function call, we use the return statement. For example,

The return statement also denotes that the function has ended. Any code after
return is not executed.

2/20/2025 K.ABINAYA Assistant Professor Sbu 15


Example 2: Function return Type

In the above example, we have created a function named find_square(). The function
accepts a number and returns the square of the number.
2/20/2025 K.ABINAYA Assistant Professor Sbu 16
Example 3: Add Two Numbers

2/20/2025 K.ABINAYA Assistant Professor Sbu 17


Benefits of Using Functions
1. Code Reusable - We can use the same function multiple times in our program
which makes our code reusable. For example,

1. Code Readability - Functions help us break our code into chunks to make our
program readable and easy to understand.

2/20/2025 K.ABINAYA Assistant Professor Sbu 18


Python Methods

2/20/2025 K.ABINAYA Assistant Professor Sbu 19


In the above example, we have created a class named Room with:
➢ Attributes: length and breadth
➢ Method: calculate_area()
➢ Here, we have created an object named study_room from the Room class. We then
used the object to assign values to attributes: length and breadth.
➢ Notice that we have also used the object to call the method inside the class,

➢ Here, we have used the . notation to call the method. Finally, the statement inside the
method is executed.

2/20/2025 K.ABINAYA Assistant Professor Sbu 20


Constructor in Python
➢ In object-oriented programming, A constructor is a special method used to create and
initialize an object of a class. This method is defined in the class.
➢ The constructor is executed automatically at the time of object creation.
➢ The primary use of a constructor is to declare and initialize data member/ instance
variables of a class. The constructor contains a collection of statements (i.e., instructions)
that executes at the time of object creation to initialize the attributes of an object.
➢ For example, when we execute obj = Sample(), Python gets to know that obj is an object
of class Sample and calls the constructor of that class to create an object.
➢ Note: In Python, internally, the __new__ is the method that creates the object, and
__del__ method is called to destroy the object when the reference count for that object
becomes zero.

2/20/2025 K.ABINAYA Assistant Professor Sbu 21


In Python, Object creation is divided into two parts in Object Creation and Object initialization.

➢ Internally, the __new__ is the method that creates the object


➢ And, using the __init__() method we can implement constructor to initialize the object. Syntax
of a constructor.

Where,
➢ def: The keyword is used to define function.
➢ __init__() Method: It is a reserved method. This method gets called as soon as an object of a
class is instantiated.
➢ self: The first argument self refers to the current object. It binds the instance to the __init__()
method. It’s usually named self to follow the naming convention.
Note: The __init__() method arguments are optional. We can define a constructor with any number
of arguments.

2/20/2025 K.ABINAYA Assistant Professor Sbu 22


Python Constructors
Example: Create a Constructor in Python

2/20/2025 K.ABINAYA Assistant Professor Sbu 23


Python Non-Parameterized Constructor
The non-parameterized constructor uses when we do not want to manipulate the value or
the constructor that has only self as an argument. Consider the following example.

2/20/2025 K.ABINAYA Assistant Professor Sbu 24


Python Parameterized Constructor
The parameterized constructor has multiple parameters along with the self. Consider the
following example.

2/20/2025 K.ABINAYA Assistant Professor Sbu 25


Python Default Constructor
When we do not include the constructor in the class or forget to declare it, then that
becomes the default constructor. It does not perform any task but initializes the objects.
Consider the following example.

2/20/2025 K.ABINAYA Assistant Professor Sbu 26


More than One Constructor in Single class

➢ In the above code, the object st called the second constructor whereas both have the
same configuration.
➢ The first method is not accessible by the st object. Internally, the object of the class
will always call the last constructor if the class has multiple constructors.

2/20/2025 K.ABINAYA Assistant Professor Sbu 27


Python built-in class functions

SN Function Description
1 getattr(obj,name,default) It is used to access the attribute of the
object.
2 setattr(obj, name,value) It is used to set a particular value to the
specific attribute of an object.

3 delattr(obj, name) It is used to delete a specific attribute.

4 hasattr(obj, name) It returns true if the object contains some


specific attribute.

2/20/2025 K.ABINAYA Assistant Professor Sbu 28


2/20/2025 K.ABINAYA Assistant Professor Sbu 29
Built-in class attributes
Along with the other attributes, a Python class also contains some built-in class attributes
which provide information about the class.
The built-in class attributes are given in the below table.
SN Attribute Description
1 __dict__ It provides the dictionary containing the information about the class
namespace.

2 __doc__ It contains a string which has the class documentation

3 __name__ It is used to access the class name.


4 __module It is used to access the module in which, this class is defined.
__

5 __bases__ It contains a tuple including all base classes.


2/20/2025 K.ABINAYA Assistant Professor Sbu 30
2/20/2025 K.ABINAYA Assistant Professor Sbu 31
Polymorphism in Python
➢ The literal meaning of polymorphism is the condition of occurrence in different
forms.
➢ Polymorphism is a very important concept in programming. It refers to the use of a
single type entity (method, operator or object) to represent different types in different
scenarios.

➢ we can see that a single operator + has been used to carry out different operations for
distinct data types. This is one of the most simple occurrences of polymorphism in
Python.

2/20/2025 K.ABINAYA Assistant Professor Sbu 32


Function Polymorphism in Python
➢ There 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. Let's
look at some example use cases of the function.

2/20/2025 K.ABINAYA Assistant Professor Sbu 33


Class Polymorphism in Python
➢ We can use the concept of polymorphism while creating class methods as Python
allows different classes to have methods with the same name.
➢ We can then later generalize calling these methods by disregarding the object we are
working with.

2/20/2025 K.ABINAYA Assistant Professor Sbu 34


Python inheritance
➢ In inheritance an object is based on another object. When inheritance is implemented,
the methods and attributes that were defined in the base class will also be present in the
inherited class.
➢ This is generally done to abstract away similar code in multiple classes.
➢ The abstracted code will reside in the base class and the previous classes will now
inherit from the base class.

2/20/2025 K.ABINAYA Assistant Professor Sbu 35


2/20/2025 K.ABINAYA Assistant Professor Sbu 36
Polymorphism and Inheritance
Like in other programming languages, the child classes in Python also inherit methods and
attributes from the parent class. We can redefine certain methods and attributes specifically
to fit the child class, which is known as Method Overriding.

2/20/2025 K.ABINAYA Assistant Professor Sbu 37


Method Overloading, a way to create multiple methods with the same name but
different arguments, is not possible in Python.

2/20/2025 K.ABINAYA Assistant Professor Sbu 38


Method Overloading
• Two or more methods have the same name but different numbers of parameters or
different types of parameters, or both. These methods are called overloaded methods
and this is called method overloading.

Method Overriding
• Method overriding is an ability of any object-oriented programming language that
allows a subclass or child class to provide a specific implementation of a method
that is already provided by one of its super-classes or parent classes.

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

2/20/2025 K.ABINAYA Assistant Professor Sbu 39


Method Overloading Method Overriding

1. Same name methods but have 1. Same name methods but have
different signatures eg. Sum(a+b) same signatures
Sum(a+b+c)

2. Multiple methods of same names 2. Multiple methods of same names


are in same class are in different class

3. No need of inheritance as it is in 3. Inheritance is required as it is in


single class different class

2/20/2025 K.ABINAYA Assistant Professor Sbu 40


2/20/2025 K.ABINAYA Assistant Professor Sbu 41
Method 1 (Not The Most Efficient Method):
We can use the arguments to make the same function work differently i.e. as per the
arguments.

2/20/2025 K.ABINAYA Assistant Professor Sbu 42


Method 2 (Not the efficient one):
We can achieve method overloading in python by user defined function using “None”
keyword as default parameter.

2/20/2025 K.ABINAYA Assistant Professor Sbu 43


Method 3:Here's how we will use the decorators so that the functions have
the features of method overloading:

2/20/2025 K.ABINAYA Assistant Professor Sbu 44


Method Overriding

2/20/2025 K.ABINAYA Assistant Professor Sbu 45


Method overriding with multiple and multilevel inheritance
Multiple Inheritance: When a class is derived from more than one base class it is
called multiple Inheritance.

2/20/2025 K.ABINAYA Assistant Professor Sbu 46


Multilevel Inheritance: When we have a child and grandchild relationship

2/20/2025 K.ABINAYA Assistant Professor Sbu 47


Feature Multiple Inheritance Multilevel Inheritance
Definition A class inherits from more than A class inherits from another derived
one parent class. class, forming a hierarchy.
Structure One child class has multiple A parent-child-grandchild relationship.
parent classes.

Code More complex due to multiple Less complex as inheritance follows a


Complexity parent classes. linear hierarchy.
Example A class HybridCar inheriting from A class SportsCar inheriting from Car,
Scenario both ElectricCar and PetrolCar. which in turn inherits from Vehicle.

2/20/2025 K.ABINAYA Assistant Professor Sbu 48


Calling the Parent’s method within the overridden method
➢ Parent class methods can also be called within the overridden methods. This can
generally be achieved by two ways.
➢ Using Classname: Parent’s class methods can be called by using the Parent
classname.method inside the overridden method.

2/20/2025 K.ABINAYA Assistant Professor Sbu 49


Using Super(): The super() function in Python is used to call a method from the parent
class inside a subclass.
It allows a subclass to inherit and extend the functionality of the parent class without
explicitly referring to the parent class name.

2/20/2025 K.ABINAYA Assistant Professor Sbu 50


Polymorphism with Function and Objects
We can create polymorphism with a function that can take any object as a
parameter and execute its method without checking its class type. Using this, we can call
object actions using the same function instead of repeating method calls.

2/20/2025 K.ABINAYA Assistant Professor Sbu 51


Polymorphism In Built-in Methods
➢ The word polymorphism is taken from the Greek words poly (many) and
morphism (forms). It means a method can process objects differently
depending on the class type or data type.
➢ The built-in function reversed(obj) returns the iterable by reversing the given
object. For example, if you pass a string to it, it will reverse it. But if you pass a
list of strings to it, it will return the iterable by reversing the order of elements (it
will not reverse the individual string).
➢ Let us see how a built-in method process objects having different data types.

2/20/2025 K.ABINAYA Assistant Professor Sbu 52


2/20/2025 K.ABINAYA Assistant Professor Sbu 53
Encapsulation in Python
➢ In Python describes the concept of bundling data and methods within a single
unit.
➢ So, for example, when you create a class, it means you are implementing
encapsulation.
➢ A class is an example of encapsulation as it binds all the data members (instance
variables) and methods into a single unit.
➢ In this example, we create an Employee class by defining employee attributes such
as name and salary as an instance variable and implementing behavior using
work() and show() instance methods.

2/20/2025 K.ABINAYA Assistant Professor Sbu 54


2/20/2025 K.ABINAYA Assistant Professor Sbu 55
Python Access Modifiers
Let us see the access modifiers in Python to understand the concept of Encapsulation and data hiding −
➢ public
➢ private
➢ protected
The public Access Modifier
The public member is accessible from inside or outside the class.
The private Access Modifier
The private member is accessible only inside class. Define a private member by prefixing the member
name with two underscores, for example: __age
The protected Access Modifier
The protected member is accessible. from inside the class and its sub-class. Define a protected member
by prefixing the member name with an underscore, for example: _points

2/20/2025 K.ABINAYA Assistant Professor Sbu 56


Public Member
➢ Public data members are accessible within and outside of a class. All member variables of the class are by
default public.

2/20/2025 K.ABINAYA Assistant Professor Sbu 57


Private Member
➢ We can protect variables in the class by marking them private. To define a private variable add
two underscores as a prefix at the start of a variable name.
➢ Private members are accessible only within the class, and we can’t access them directly from the
class objects.

2/20/2025 K.ABINAYA Assistant Professor Sbu 58


In the above example, the salary is a private variable. As you know, we can’t access the private variable
from the outside of that class.
We can access private members from outside of a class using the following two approaches
Create public method to access private members
Use name mangling
Public method to access private members
Example: Access Private member outside of a class using an instance method

2/20/2025 K.ABINAYA Assistant Professor Sbu 59


Name Mangling to access private members
We can directly access private and protected variables from outside of a class through name
mangling. The name mangling is created on an identifier by adding one leading underscores and two
trailing underscore, like this _classname__dataMember, where classname is the current class, and data
member is the private variable name.

2/20/2025 K.ABINAYA Assistant Professor Sbu 60


Protected Member
➢ Protected members are accessible within the class and also available to its sub-classes. To define a protected
member, prefix the member name with a single underscore _.
➢ Protected data members are used when you implement inheritance and want to allow data members access to
only child classes.

2/20/2025 K.ABINAYA Assistant Professor Sbu 61


Getters and Setters in Python
➢ Use the getter method to access data members and
➢ The setter methods to modify the data members.
➢ In Python, private variables are not hidden fields like in other programming
languages.
➢ The getters and setters methods are often used when:
When we want to avoid direct access to private variables
To add validation logic for setting a value

2/20/2025 K.ABINAYA Assistant Professor Sbu 62


2/20/2025 K.ABINAYA Assistant Professor Sbu 63
Data Abstraction in Python
➢ Data Abstraction in Python is the process of hiding the real implementation of an
application from the user and emphasizing only on usage of it.
➢ Basically, Abstraction focuses on hiding the internal implementations of a process or
method from the user.
➢ In this way, the user knows what he is doing but not how the work is being done.

2/20/2025 K.ABINAYA Assistant Professor Sbu 64


Abstract Class
➢ The classes that cannot be instantiated. This means that we cannot create objects of
an abstract class and these are only meant to be inherited.
➢ Then an object of the derived class is used to access the features of the base class.
➢ These are specifically defined to lay a foundation of other classes that exhibit
common behavior or characteristics.
Consider an example where we create an abstract class Fruit.
➢ We derive two classes Mango and Orange from the Fruit class that implement the
methods defined in this class.
➢ Here the Fruit class is the parent abstract class and the classes Mango and Apple
become the sub/child classes.
➢ We won’t be able to access the methods of the Fruit class by simply creating an
object, we will have to create the objects of the derived classes: Mango and Apple to
access the methods.

2/20/2025 K.ABINAYA Assistant Professor Sbu 65


2/20/2025 K.ABINAYA Assistant Professor Sbu 66
Working of Abstract Class
➢ Python does not provide the abstract class itself. To achieve that, we use the abc
module of Python, which provides the base and necessary tools for defining Abstract
Base Classes (ABC).
➢ We can create our own ABCs with this module.

➢ ABC is defined in a way that the abstract methods in the base class are created by
decorating with the @abstractmethod keyword and the concrete methods are
registered as implementations of the base class.

2/20/2025 K.ABINAYA Assistant Professor Sbu 67


Concrete Methods in Abstract Base Class in Python
We now know that we use abstract classes as a template for other similarly
characterized classes. Using this, we can define a structure, but do not need to
provide complete implementation for every method, such as:

2/20/2025 K.ABINAYA Assistant Professor Sbu 68


➢ There are methods that have the same implementation for all subclasses as well.
There are characteristics that exhibit the properties of the abstract class and so, must
be implemented in the abstract class itself.
➢ Otherwise, it will lead to repetitive code in all the inherited classes. These methods
are called concrete methods.

2/20/2025 K.ABINAYA Assistant Professor Sbu 69


2/20/2025 K.ABINAYA Assistant Professor Sbu 70
2/20/2025 K.ABINAYA Assistant Professor Sbu 71
Data Hiding
➢ Data hiding also minimizes system complexity for increase robustness by limiting
interdependencies between software requirements. Data hiding is also known as
information hiding.
➢ In class, if we declare the data members as private so that no other class can access
the data members, then it is a process of hiding data.
Data Hiding in Python:
➢ The Python document introduces Data Hiding as isolating the user from a part of
program implementation. Some objects in the module are kept internal, unseen, and
unreachable to the user.
➢ Modules in the program are easy enough to understand how to use the application,
but the client cannot know how the application functions. Thus, data hiding imparts
security, along with discarding dependency.
➢ Data hiding in Python is the technique to defend access to specific users in the
application.

2/20/2025 K.ABINAYA Assistant Professor Sbu 72


2/20/2025 K.ABINAYA Assistant Professor Sbu 73
2/20/2025 K.ABINAYA Assistant Professor Sbu 74
Python Module and Import class

2/20/2025 K.ABINAYA Assistant Professor Sbu 75

You might also like