Unit 2 DS Basics of OOP Concepts
Unit 2 DS Basics of OOP Concepts
Oriented Programming
PREPARED AND COMPILED BY:
D.R. GANDHI
LECTURER IN INFORMATION TECHNOLOGY
Learning Outcomes:
Oops Concepts
Class and Object
Constructors
Types of methods
Instance method
Class method
static method
Data Encapsulation
Inheritance - single, multiple, multi-level, hierarchical, hybrid
Polymorphism through inheritance
Abstraction - abstract class
Procedural Programming:
Class
Objects
Polymorphism
Encapsulation
Inheritance
Data Abstraction
OOP Concepts
Class:-
The class can be defined as a collection of objects.
It is a logical entity that has some specific attributes and methods.
A class is a blueprint for the object.
To create an object we require a model or plan or blueprint which is nothing
but class.
A class contains the properties (attribute) and action (behavior) of the
object.
Properties represent variables, and the methods represent actions. Hence
class includes both variables and methods.
OOP Concepts
Object:-
Object is an instance of a class.
The physical existence of a class is nothing but an object.
In other words, the object is an entity that has a state and behavior.
It may be any real-world object like the mouse, keyboard, laptop, etc.
OOP Concepts
Objects have two characteristics: They have states and behaviors (object
has attributes and methods attached to it) Attributes represent its state,
and methods represent its behavior. Using its methods, we can modify its
state.
In short, Every object has the following property.
Identity: Every object must be uniquely identified.
State: An object has an attribute that represents a state of an object, and it
also reflects the property of an object.
Behavior: An object has methods that represent its behavior.
OOP Concepts
Syntax of a constructor:-
def __init__(self):
# body of the constructor
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.
Example: Create a Constructor in Python
Inside Constructor
All variables initialized
Hello, my name is Emma
Constructor:
Note:
For every object, the constructor will be executed only once. For example, if we
create four objects, the constructor is called four times.
In Python, every class has a constructor, but it’s not required to define it explicitly.
Defining constructors in class is optional.
Python will provide a default constructor if no constructor is defined.
Constructor:
Types of Constructors:-
In Python, we have the following three types of constructors.
Default Constructor
Non-parametrized constructor
Parameterized constructor
Constructor:
Default Constructor:-
Python will provide a default constructor if no constructor is defined. Python adds a
default constructor when we do not include the constructor in the class or forget to
declare it. It does not perform any task but initializes the objects. It is an empty
constructor without a body.
If you do not implement any constructor in your class or forget to declare it, the Python
inserts a default constructor into your code on your behalf. This constructor is known
as the default constructor.
It does not perform any task but initializes the objects. It is an empty constructor
without a body.
Note:
If you implement your constructor, then the default constructor will not be added.
Constructor:
Output:
Inside Display
Constructor:
Non-Parametrized Constructor:-
A constructor without any arguments is called a non-parameterized constructor.
This type of constructor is used to initialize each object with default values.
This constructor doesn’t accept the arguments during object creation.
Instead, it initializes every object with the same set of values.
Constructor:
Parameterized Constructor:-
A constructor with defined parameters or arguments is called a parameterized
constructor. We can pass different values to each object at the time of creation using
a parameterized constructor.
The first parameter to constructor is self that is a reference to the being constructed,
and the rest of the arguments are provided by the programmer. A parameterized
constructor can have any number of arguments.
For example, consider a company that contains thousands of employees. In this
case, while creating each employee object, we need to pass a different name, age,
and salary. In such cases, use the parameterized constructor.
Constructor:
Emma 23 7500
Kelly 25 8500
Constructor:
Emma 12 7
Kelly 13 7
Class Attributes
Define a Book class with the following attributes: Title, Author (Full name),Price.
Define a constructor used to initialize the attributes of the method with values
entered by the user.
Set the View() method to display information for the current book.
Example
If we use instance variables inside a method, such methods are called instance
methods.
The instance method performs a set of actions on the data/value provided by the
instance variables.
A instance method is bound to the object of the class.
It can access or modify the object state by changing the value of a instance variables
When we create a class in Python, instance methods are used regularly. To work
with an instance method, we use the self keyword.
We use the self keyword as the first parameter to a method. The self refers to the
current object.
Any method we create in a class will automatically be created as an instance method
unless we explicitly tell Python that it is a class or static method.
Instance Method:
Instance Method:
First Student
Name: Jessa Age: 14
Second Student
Name: Kelly Age: 16
Instance Method:
Notes:
Inside any instance method, we can use self to access any data or method that
reside in our class. We are unable to access it without a self parameter.
An instance method can freely access attributes and even modify the value of
attributes of an object by using the self parameter.
By Using self.__class__ attribute we can access the class attributes and change the
class state. Therefore instance method gives us control of changing the object as well
as the class state.
Instance Method:
class VIII
Roll Number: 20 Name: Emma Age: 14
class IX
Roll Number: 35 Name: Emma Age: 15
Create Instance Variables in
Instance Method:
Till the time we used constructor to create instance attributes.
instance attributes are not specific only to the __init__() method; they can be defined
elsewhere in the class.
Create Instance Variables in
Instance Method:
Roll Number: 20 Name: Emma Age: 14 Marks: 75
Class Method:
Class methods are methods that are called on the class itself, not on a specific object
instance. Therefore, it belongs to a class level, and all class instances share a class
method.
A class method is bound to the class and not the object of the class. It can access
only class variables.
It can modify the class state by changing the value of a class variable that would
apply across all the class objects.
In method implementation, if we use only class variables, we should declare such
methods as class methods. The class method has a cls as the first parameter, which
refers to the class.
The class method can be called using ClassName.method_name() as well as by
using an object of the class.
Create Class Method Using
@classmethod Decorator
We must explicitly tell Python that it is a class method using the @classmethod
decorator or classmethod() function.
Class methods are defined inside a class, and it is pretty similar to defining a regular
function.
inside the class method, we use the cls keyword as a first parameter to access class
variables. Therefore the class method gives us control of changing the class state.
The class method can only access the class attributes, not the instance attributes.
Class methods are used when we are dealing with factory methods. Factory
methods are those methods that return a class object for different use cases.
Thus, factory methods create concrete implementations of a common interface.
Class Method:
Jessa's age is: 20
Joy's age is: 27
Create Class Method Using
@classmethod Decorator
To make a method as class method, add @classmethod decorator before the method
definition, and add cls as the first parameter to the method.
The @classmethod decorator is a built-in function decorator. In Python, we use the
@classmethod decorator to declare a method as a class method. The @classmethod
decorator is an expression that gets evaluated after our function is defined.
The @classmethod decorator is used for converting calculate_age() method to a class
method.
The calculate_age() method takes Student class (cls) as a first parameter and returns
constructor by calling Student(name, date.today().year - birthYear), which is
equivalent to Student(name, age)
Create Class Method Using
classmethod() function
Apart from a decorator, the built-in function classmethod() is used to convert a
normal method into a class method.
The classmethod() is an inbuilt function in Python, which returns a class method for
a given function.
Syntax:
classmethod(function)
function: It is the name of the method you want to convert as a class method.
It returns the converted class method.
A classmethod() function is the older way to create the class method in Python. In a
newer version of Python, we should use the @classmethod decorator to create a class
method.
Create Class Method Using
classmethod() function
Completed task_1
Completed task_2
Completed task_3
Completed task_1
destructor:
Inside Constructor
Object initialized
Hello, my name is Emma
Inside destructor
Object destroyed
Encapsulation:
Encapsulation in Python describes the concept of bundling data and
methods within a single unit.
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.
Encapsulation:
Using encapsulation, we can hide an object’s internal representation
from the outside. This is called information hiding.
Encapsulation allows us to restrict accessing variables and methods
directly and prevent accidental data modification by creating private
data members and methods within a class.
Encapsulation is a way to can restrict access to methods and
variables from outside of class.
Whenever we are working with the class and dealing with sensitive
data, providing access to all variables used within the class is not a
good choice.
Access specifier:
Access specifiers or access modifiers in python programming are used to
limit the access of class variables and class methods outside of class while
implementing the concepts of inheritance.
This can be achieved by: Public, Private and Protected keyword.
There are three types of access specifiers or access modifiers
1). Public access modifier
2). Private access modifier
3). Protected access modifier
Access specifier:
Access specifier:
Access specifier:
Public Access Modifier:-
All the variables and methods (member functions) in python are by default
public.
Any instance variable in a class followed by the ‘self’ keyword ie.
self.var_name are public accessed.
Public data members are accessible within and outside of a class.
Access specifier:
Name: Jessa 14
Name: Jessa 16
Access specifier:
Advantages of Encapsulation
Security: The main advantage of using encapsulation is the security of the
data. Encapsulation protects an object from unauthorized access. It allows
private and protected access levels to prevent accidental data modification.
Data Hiding: The user would not be knowing what is going on behind the
scene. They would only be knowing that to modify a data member, call the
setter method. To read a data member, call the getter method. What these
setter and getter methods are doing is hidden from them.
Simplicity: It simplifies the maintenance of the application by keeping
classes separated and preventing them from tightly coupling with each
other.
Aesthetics: Bundling data and methods within a class makes code more
readable and maintainable
inheritance
Types Of Inheritance :-
Single inheritance
Multiple Inheritance
Multilevel inheritance
Hierarchical Inheritance
Hybrid Inheritance
inheritance
Single Inheritance:-
In single inheritance, a child class inherits from a single-parent class.
Here is one child class and one parent class.
inheritance
Addition value1 : 10
Addition value2 : 15
Added value : 25
multiplication value1 : 20
multiplication value2 : 30
Multiplied value : 600
subraction value1 : 50
subraction value2 : 30
Subracted value : 20
inheritance
Multiple Inheritance:-
In multiple inheritance, one child class can inherit from multiple
parent classes. So here is one child class and multiple parent
classes.
inheritance
Multilevel Inheritance:-
In multilevel inheritance, a class inherits from a child class or
derived class.
Suppose three classes A, B, C.
A is the superclass,
B is the child class of A,
C is the child class of B.
inheritance
Hierarchical Inheritance:-
In Hierarchical inheritance, more than one child class is derived from
a single parent class.
In other words, we can say one parent class and multiple child
classes.
inheritance
This is Vehicle
Car name is: BMW
This is Vehicle
Truck name is: Ford
inheritance
Hybrid Inheritance:-
When inheritance is consists of multiple types or a combination of
different inheritance is called hybrid inheritance.
inheritance
Circle
I am a two-dimensional shape.
Squares have each angle equal
to 90 degrees.
153.93804002589985
Polymorphism
Polymorphism In Class methods:-
Polymorphism with class methods is useful when we group different
objects having the same method.
we can add them to a list or a tuple, and we don’t need to check the
object type before calling their methods.
Instead, Python will check object type at runtime and call the correct
method.
Thus, we can call the methods without being concerned about which
class type each object is. We assume that these methods exist in
each class.
Polymorphism
Petrol
Max speed 350
Diesel
Max speed is 240
Polymorphism
Polymorphism In Class methods:-
As you can see, we have created two classes Ferrari and BMW. They
have the same instance method names fuel_type() and max_speed().
However, we have not linked both the classes nor have we used
inheritance.
We packed two different objects into a tuple and iterate through it
using a car variable.
It is possible due to polymorphism because we have added the same
method in both classes Python first checks the object’s class type
and executes the method present in its class.
Polymorphism
Polymorphism In Function and Object:-
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.
Polymorphism
Petrol
Max speed 350
Diesel
Max speed is 240
Polymorphism
Polymorphism In Built-in Methods:-
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).
Polymorphism
Polymorphism In In Built-in Methods:-
Reverse string
evitanYP
Reverse list
Kelly Jessa Emma
Polymorphism
Method Overloading:-
The process of calling the same method with different parameters is
known as method overloading.
Python does not support method overloading.
Python considers only the latest defined method even if you overload
the method.
Python will raise a TypeError if you overload the method.
Polymorphism
Method Overloading:-
Polymorphism
Method Overloading:-
300
JessRoy
[10, 20, 30, 'jessa', 'emma', 'kelly']
Polymorphism
Overloading + operator for custom objects:-
Suppose we have two objects, and we want to add these two objects
with a binary + operator. However, it will throw an error if we
perform addition because the compiler doesn’t add two objects
Polymorphism
Overloading + operator for custom objects:-
Python provides some special or magic function that is automatically
invoked when associated with that particular operator.
For example, when we use the + operator, the magic method
__add__() is automatically invoked.
Internally + operator is implemented by using __add__() method. We
have to override this method in our class if you want to add two
custom objects.
Polymorphism
Overloading + operator for custom objects:-