Object Oriented Programming
Object Oriented Programming
What is an OOP?
Object-oriented programming is a programming
paradigm that structures programs so that properties and
behaviors (actions) are bundled into individual objects.
For instance, an object could represent a person
with properties like a name, age, address, and behaviors such
as walking, talking, breathing, and running.
Why chooses OOP?
OOP offers the following advantages:
Provides a clear program structure, which makes it easy to map
real-world problems and their solutions.
Facilitates easy maintenance and modification of existing code.
Enhances program modularity because each object exists
independently and new features can be added easily without
disturbing the existing ones.
Presents a good framework for code libraries where the
programmer can easily adapt and modify the supplied
components.
code reusability
Class
The class can be defined as a collection of objects.
It is a logical entity that has some specific attributes and
methods.
For example: if you have an employee class, then it should
contain an attribute and method, i.e., name, age, salary, email,
etc.
Syntax
class ClassName:
attributes and methods
Example-1
Object
an object is a physical entity.
A unique instance of a data structure that's defined by its class.
An object comprises both data members (class variables and
instance variables) and methods.
Instance variable − A variable that is defined inside a method
and belongs only to the current instance of a class.
Class variable − A variable that is shared by all instances of a
class. Class variables are defined within a class but outside any
of the class's methods.
Example
An object consists of
State: It is represented by the attributes of an object. It also
reflects the properties of an object.
Behavior: It is represented by the methods of an object. It also
reflects the response of an object to other objects.
Identity: It gives a unique name to an object and enables one
object to interact with other objects.
Syntax:
<object-name> = <class-name>(<arguments>)
self-parameter
The self-parameter refers to the current instance of the class
and accesses the class variables.
We can use anything instead of self, but it must be the first
parameter of any function which belongs to the class.
Constructor
A constructor is a special type of method (function) that 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 the class is created.
In Python the __init__() method is called the constructor and is
always called when an object is created.
Syntax
def __init__(self):
# body of the constructor
Constructors can be of two types.
1. Parameterized Constructor
2. Non-parameterized Constructor
Constructor definition is executed when we create the object
of this class.
Parameterized Constructor
The parameterized constructor has multiple parameters along
with the self.
Example
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.
Example
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.
Example
Python Inheritance
Inheritance allows us to define a class that inherits all the
methods and properties from another class.
Parent class is the class being inherited from, also called a base
class.
Child class is the class that inherits from another class, also
called derived class.
The benefits of inheritance are:
It represents real-world relationships well.
It provides the 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.
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.
Inheritance offers a simple, understandable model structure.
Less development and maintenance expenses result from an
inheritance.
Python Inheritance Syntax
Class BaseClass:
{Body}
Class DerivedClass(BaseClass):
{Body}
Types of Inheritance in Python
Single Inheritance:
Single inheritance enables a derived class to inherit properties
from a single parent class, thus enabling code reusability and
the addition of new features to existing code.
Example
class Parent:
def func1(self):
print("This function is in parent class.")
class Child(Parent):
def func2(self):
print("This function is in child class.")
object = Child()
object.func1()
object.func2()
Multiple Inheritance:
When a class can be derived from more than one base class this
type of inheritance is called multiple inheritances.
In multiple inheritances, all the features of the base classes are
inherited into the derived class.
Example:
class Mother:
mothername = ""
def mother(self):
print(self.mothername)
class Father:
fathername = ""
def father(self):
print(self.fathername)
Example:
class Grandfather:
def __init__(self, grandfathername):
self.grandfathername = grandfathername
class Father(Grandfather):
def __init__(self, fathername, grandfathername):
self.fathername = fathername
Grandfather.__init__(self, grandfathername)
class Son(Father):
def __init__(self, sonname, fathername,
grandfathername):
self.sonname = sonname
Father.__init__(self, fathername, grandfathername)
def print_name(self):
print('Grandfather name :', self.grandfathername)
print("Father name :", self.fathername)
print("Son name :", self.sonname)
Hierarchical Inheritance:
When more than one derived class is created from a single base
this type of inheritance is called hierarchical inheritance.
In this program, we have a parent (base) class and two child
(derived) classes.
Example:
#Base class
class Parent:
def func1(self):
print("This function is in parent class.")
# Derived class1
class Child1(Parent):
def func2(self):
print("This function is in child 1.")
# Derivied class2
class Child2(Parent):
def func3(self):
print("This function is in child 2.")
# Driver's code
object1 = Child1()
object2 = Child2()
object1.func1()
object1.func2()
object2.func1()
object2.func3()
Python also has a super() function that will make the child class
inherit all the methods and properties from its parent
Method Overloading
Overloading is a method or operator that can do different
functionalities with the same name.
Methods in Python can be called with zero, one, or more
parameters. This process of calling the same method in different
ways is called method overloading.
Two methods cannot have the same name in Python; hence
method overloading is a feature that allows the same operator
to have different meanings.
Advantage of Method Overloading
✓ reduces complexities
✓ improves the quality of the code
✓ is also used for reusability and easy accessibility
Example
class Person:
def Hello(self, name=None):
if name is not None:
print('Hello ' + name)
else:
print('Hello ')
obj = Person()
obj.Hello()
obj.Hello('Ramesh')
overriding method
The overriding method allows a child class to provide a specific
implementation of a method that is already provided by one of
its parent classes.
Example
class Employee:
def __init__(self, name, base_pay):
self.name = name
self.base_pay = base_pay
def get_pay(self):
return self.base_pay
class SalesEmployee(Employee):
def __init__(self, name, base_pay, sales_incentive):
super().__init__(name,base_pay)
self.sales_incentive = sales_incentive
def get_pay(self):
return self.base_pay + self.sales_incentive
if __name__ == '__main__':
john = SalesEmployee('John', 5000, 1500)
print(john.get_pay())
def func(obj):
obj.type()
obj.color()
obj_tomato = Tomato()
obj_apple = Apple()
func(obj_tomato)
func(obj_apple)
Polymorphism with Class Methods
class India():
def capital(self):
print("New Delhi")
def language(self):
print("Hindi and English")
class USA():
def capital(self):
print("Washington, D.C.")
def language(self):
print("English")
obj_ind = India()
obj_usa = USA()
for country in (obj_ind, obj_usa):
country.capital()
country.language()
Encapsulation In Python
The process of wrapping up variables and methods into a single
entity is known as Encapsulation.
When working with classes and dealing with sensitive data,
providing global access to all the variables used within the
program is not a good choice.
Encapsulation offers a way for us to access the required variables
without providing the program full-fledged access to any of
those variables.
Updating, modifying, or deleting data from variables can be
done through the use of methods that are defined specifically for
the purpose.
The benefit of using this approach to programming is improved
control over the input data and better security.
Access modifiers
Access modifiers limit access to the variables and functions of a
class. Python uses three types of access modifiers; they are
- private, public, and protected.
Public members
Public members are accessible anywhere from the class. All the
member variables of the class are by default public.
Example
class Person:
def __init__(self, name, age=0):
self.name = name
self.age = age
def display(self):
print(self.name)
print(self.age)
def display(self):
print(self.name)
print(self._age)
Private members
Private members are accessible within the class. To define a private
member, prefix the member’s name with a double underscore
“__”.
Example
class Person:
def __init__(self, name, age=0):
self.name = name
self.__age = age
def display(self):
print(self.name)
print(self.__age)
def getAge(self):
print(self.__age)