Module -V
Python Object Oriented Programming
Object Oriented Programming in Python
• Object-oriented programming (OOP) is a programming paradigm
based on the concept of "objects".
• The object contains both data and code:
• Data in the form of properties (often known as attributes),
• and code, in the form of methods (actions object can perform)
• An object-oriented paradigm is to design the program using classes
and objects.
Object Oriented Programming in Python
• Python programming language supports different programming
approaches like functional programming, modular programming.
• One of the popular approaches is object-oriented programming
(OOP)
• solve programming problem by creating objects
Python OOPS concepts
Inheritance
Python OOPS concepts : Object
• An object has the following two characteristics:
Attribute
Behavior
• For example, A Car is an object, as it has the following properties:
• name, price, color : attributes
• breaking, acceleration : behavior
Class and Objects
• In Python, everything is an object.
• 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.
Class and Objects
Object is an instance of a class.
• The physical existence of a class is an object.
• The object is an entity that has a state and behavior.
• It may be any real-world object like the mouse, keyboard,
laptop, etc.
Class and Objects
Creating Class and Objects in Python
• Uses the keyword class to define a Class.
• Uses __init__() to set the initial state of the object by assigning the
values of the object’s properties
class GeekforGeeks:
# default constructor
def __init__(test):
test.geek = "GeekforGeeks"
# a method for printing data members
def print_Geek(self):
print(self.geek)
# creating object of the class
obj = GeekforGeeks()
# calling the instance method using the object obj
obj.print_Geek()
Class Attributes and Methods in Python
• In Class, attributes can be defined into two parts:
• Instance variables:
• The instance variables are attributes attached to an instance of a class.
• We define instance variables in the constructor (the __init__() method of a
class).
• Class Variables:
• A class variable is a variable that is declared inside of class, but outside of any
instance method or __init()__ method.
Creating Class and Objects
• In the above example, we created a Class with the name Employee.
• Next, we defined two attributes name and salary.
• Next, in the __init__() method, we initialized the value of attributes.
This method is called as soon as the object is created. The init method
initializes the object.
• Finally, from the Employee class, we created two objects, Emma and
Harry.
• Using the object, we can access and modify its attributes.
Creating Class and Objects
Abstraction
• Abstraction is a technique that involves hiding the implementation
details of a class and only exposing the essential features of the
class to the user.
• This allows the user to work with objects of the class without having
to worry about the details of how the class works.
Abstraction
Define a class that can add and subtract two
numbers
What Does if __name__ == "__main__" Do in
Python?
• Python’s if __name__ == "__main__" idiom is just a normal
conditional block:
• It Allows You to Execute Code When the File Runs as a Script, but Not
When It’s Imported as a Module
Python class as Modules
Person.py
Python class as Modules
Exercise 1
• Write a Rectangle class in Python language, allowing you to build a
rectangle with length and width attributes.
• Create a Perimeter() method to calculate the perimeter of the
rectangle and a Area() method to calculate the area of the rectangle.
• Create a method display() that display the length, width, perimeter
and area of an object created using an instantiation on rectangle
class.
Exercise 2
1.Create a Python class called BankAccount which represents a bank
account, having as attributes: accountNumber (numeric type), name
(name of the account owner as string type), balance.
2.Create a constructor with parameters: accountNumber, name, balance.
3.Create a Deposit() method which manages the deposit actions.
4.Create a Withdrawal() method which manages withdrawals actions.
5.Create an bankFees() method to apply the bank fees with a percentage of
5% of the balance account.
6.Create a display() method to display account details.
7.Give the complete code for the BankAccount class.
Encapsulation in Python
• 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 Python, we do not have access modifiers, such as public, private,
and protected
Public Access Modifier
• The members of a class that are declared public are easily
accessible from any part of the program.
• All data members and member functions of a class are
public by default.
Private Access Modifier
• The members of a class that are declared private are accessible within
the class only, private access modifier is the most secure access
modifier.
• Data members of a class are declared private by adding a double
underscore ‘__’ symbol before the data member of that class.
Protected Access Modifier
• Private - The members of a class that are declared private are
accessible within the class only, private access modifier is the most
secure access modifier.
• Data members of a class are declared protected by adding a single
underscore ‘_’ symbol before the data member of that class.
Encapsulation in Python
Python Destructors to Destroy the Object
• Destructor is a special method that is called when an object gets
destroyed.
• Destructor is used to perform the clean-up activity before destroying
the object, such as closing database connections or file handle.
• On the other hand, a constructor is used to create and initialize an
object of a class.
Destructor
• Destructor is not called manually but completely automatic
• gets called in the following two cases
• When an object goes out of scope or
• The reference counter of the object reaches 0
• special method __del__() is used to define a destructor.
• implicitly invoked when all references to the object have been deleted
• when we execute del <object_name> destructor gets called
automatically and the object gets garbage collected.
Destructor
Inheritance In Python
• In Python, inheritance is the process of inheriting the properties of
the parent class into a child class.
• The primary purpose of inheritance is the reusability of code.
• Using inheritance, we can use the existing class to create a new class
instead of recreating it from scratch.
Inheritance
Single Inheritance In Python
• Syntax
print(Employee.__mro__)
__mro__ attribute (a tuple of classes)
• In Python, the base classes of a class are stored in the __mro__
attribute (a tuple of classes).
• When you call a method or want to use an attribute, Python goes
through this tuple from left to right and tries to find that method or
attribute.
• If it doesn't find it, it goes to the next class. If it finds it, it returns the
result, the other classes are not checked.
Multiple Inheritance
• If 2 parent classes have methods/attributes with the same name, only
the first will be returned
• Python uses the __mro__ attribute to look for the methods and
attributes
• The order of the parent classes in this tuple determines which parent's
method will be returned
Inheritance In Python
Inheritance In Python
Use of super() function
• super() function is used to refer to the parent class or superclass
• allows you to call methods defined in the superclass from the
subclass
• enabling you to extend and customize the functionality inherited from
the parent class
Inheritance : Exercise 1
• Create a Bus child class that inherits from the Vehicle class. The
default fare charge of any vehicle is seating capacity * 100. If Vehicle
is Bus instance, we need to add an extra 10% on full fare as a
maintenance charge. So total fare for bus instance will become the
final amount = total fare + 10% of the total fare.
Exercise 1: Solution
Multiple Inheritance
Multiple Inheritance
Multilevel Inheritance
Hierarchical Inheritance
• When more than one derived class are created from a single base this
type of inheritance is called hierarchical inheritance.
Hybrid Inheritance
Inheritance consisting of multiple types of inheritance is called hybrid inheritance.
Polymorphism
• The word polymorphism means having many forms.
• In programming, polymorphism means the same function name (but
different signatures) being used for different types.
• The key difference is the data types and number of arguments used in
function.
• Can be achieved through
• Method overriding
• Method overloading
Polymorphism with Inheritance :
Method Overriding
• In Python, Polymorphism lets us define methods in the child class that have the same name as
the methods in the parent class.
• In inheritance, the child class inherits the methods from the parent class.
• It is possible to modify a method in a child class that it has inherited from the parent class.
• This is particularly useful in cases where the method inherited from the parent class doesn’t quite
fit the child class.
• In such cases, we re-implement the method in the child class.
• This process of re-implementing a method in the child class is known as Method Overriding.
Polymorphism with Inheritance :
Method Overriding
Polymorphism with Inheritance: Method Overriding
Method Overloading in Python
• Method overloading means creating multiple methods with the same
name but with different return types or parameters.
• Using method overloading, you can perform different operations
with the same function name by passing different arguments.
• Can be achieved through
• Using Default Arguments
• Using Variable Length Arguments
Method Overloading in Python
• Using Default Arguments
Method Overloading in Python
• Using Variable Length Arguments