Python Object-Oriented Programming (OOP)
In this series, you will learn OOP (Object Oriented Programming) in Python. OOP concepts include object, classes, constructor and encapsulation, polymorphism, and inheritance.
Python Object-Oriented Programming
This Python OOP series contains the following in-depth tutorial. You can directly read those.
- Classes and Objects in Python: You'll understand how to implement object-oriented programs by creating to create classes and objects.
- Constructors in Python: Learn How to create a constructor to initialize an object in Python. create different types of constructors.
- Python Destructors to Destroy the Object: Learn to create a destructor in Python to release the other resources object were using.
- Encapsulation in Python: Learn to implement Encapsulation in Python using class. implement Data Hiding using public, protected, and private members
- Polymorphism in Python: Learn to implement Polymorphism in Python using function overloading, method overriding, and operator overloading.
- Inheritance in Python: Learn to implement inheritance in Python. Also, learn types of inheritance and MRO (Method Resolution Order).
- Python Instance Variables: Learn to create and access instance variables. Modify values of instance variables. Understand how dynamically we can add or delete instance variables from the object
- Python Instance Methods: Learn to create and call instance methods. Understand how dynamically we can add or delete instance methods from the object
- Python Class Variables: Learn to create, modify and access class variables. Understand the difference between instance variables and class variables.
- Python Class Method: Learn to create and call class methods. Create class method using the
- Python Static Method: Learn to create and call static methods. Create static method using the @staticmethod decorator and staticmethod() function
- Python Class Method vs. Static Method vs. Instance Method: Understand the difference between all three class methods
- Python OOP Exercise: Solve this exercise to practice and understand OOP concepts.
What is 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. Python programming language supports different programming approaches like functional programming, modular programming. One of the popular approaches is object-oriented programming (OOP) to solve a programming problem is by creating objects
An object has the following two characteristics:
For example, A Car is an object, as it has the following properties:
- name, price, color as attributes
- breaking, acceleration as behavior
One important aspect of OOP in Python is to create reusable code using the concept of inheritance. This concept is also known as DRY (Don't Repeat Yourself).
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.
For example, you are creating a vehicle according to the Vehicle blueprint (template). The plan contains all dimensions and structure. Based on these descriptions, we can construct a car, truck, bus, or any vehicle. Here, a car, truck, bus are objects of Vehicle 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.
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.
Read More: Classes and Objects in Python
Class Attributes and Methods
When we design a class, we use instance variables and class variables.
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
Inside a Class, we can define the following three types of methods.
- Instance method: Used to access or modify the object attributes. If we use instance variables inside a method, such methods are called instance methods.
- Class method: Used to access or modify the class state. In method implementation, if we use only class variables, then such type of methods we should declare as a class method.
- Static method: It is a general utility method that performs a task in isolation. Inside this method, we don’t use instance or class variable because this static method doesn’t have access to the class attributes.
Read Python Class Method vs. Static Method vs. Instance Method to understand the difference between all three class methods.
Creating Class and Objects
In Python, Use the keyword
class to define a Class. In the class definition, the first string is docstring which, is a brief description of the class.
The docstring is not mandatory but recommended to use. We can get docstring using
__doc__ attribute. Use the following syntax to create a
class classname: '''documentation string''' class_suite
- Documentation string: represent a description of the
class. It is optional.
classsuite contains class attributes and methods
We can create any number of objects of a class. use the following syntax to create an object of a class.
reference_variable = classname()
OOP Example: Creating Class and Object in Python
class Employee: # class variables company_name = 'ABC Company' # constructor to initialize the object def __init__(self, name, salary): # instance variables self.name = name self.salary = salary # instance method def show(self): print('Employee:', self.name, self.salary, self.company_name) # create first object emp1 = Employee("Harry", 12000) emp1.show() # create second object emp2 = Employee("Emma", 10000) emp2.show()
Employee: Harry 12000 ABC Company Employee: Emma 10000 ABC Company
- 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.
Constructors in Python
In Python, a constructor is a special type of method used to initialize the object of a Class. The constructor will be executed automatically when the object is created. If we create three objects, the constructor is called three times and initialize each object.
The main purpose of the constructor is to declare and initialize instance variables. It can take at least one argument that is
__init()__ method is called the constructor in Python. In other words, the name of the constructor should be
A constructor is optional, and if we do not provide any constructor, then Python provides the default constructor. Every class in Python has a constructor, but it's not required to define it.
Encapsulation in Python
In Python, encapsulation is a method of wrapping data and functions into a single entity. For example, A class encapsulates all the data ( methods and variables). Encapsulation means the internal representation of an object is generally hidden from outside of the object's definition.
Need of Encapsulation
Encapsulation acts as a protective layer. We can restrict access to methods and variables from outside, and It can prevent the data from being modified by accidental or unauthorized modification. Encapsulation provides security by hiding the data from the outside world.
Read the complete guide on Encapsulation in Python.
Example: 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. But we can achieve encapsulation by using prefix single underscore and double underscore to control access of variable and method within the Python program.
class Employee: def __init__(self, name, salary): # public member self.name = name # private member # not accessible outside of a class self.__salary = salary def show(self): print("Name is ", self.name, "and salary is", self.__salary) emp = Employee("Jessa", 40000) emp.show() # access salary from outside of a class print(emp.__salary)
Name is Jessa and salary is 40000 AttributeError: 'Employee' object has no attribute '__salary'
In the above example, we create a class called
Employee. Within that class, we declare two variables
__salary. We can observe that the
name variable is accessible, but
__salary is the private variable. We cannot access it from outside of class. If we try to access it, we will get an error
Polymorphism in Python
Polymorphism in OOP is the ability of an object to take many forms. In simple words, polymorphism allows us to perform the same action in many different ways.
Polymorphism is taken from the Greek words Poly (many) and morphism (forms). Polymorphism defines the ability to take different forms.
For example, The student can act as a student in college, act as a player on the ground, and as a daughter/brother in the home. Another example in the programming language, the + operator, acts as a concatenation and arithmetic addition.
Example: Using Polymorphism in Python
For example, In the below example, calculate_area() instance method created in both Circle and Rectangle class. Thus, we can create a function that takes any object and calls the object's calculate_area() method to implement polymorphism. Using this object can perform
Polymorphism with class methods is useful when we want objects to perform the same action in different ways. In the below example, both objects calculate the area (same action) but in a different way (different formulas)
class Circle: pi = 3.14 def __init__(self, redius): self.radius = redius def calculate_area(self): print("Area of circle :", self.pi * self.radius * self.radius) class Rectangle: def __init__(self, length, width): self.length = length self.width = width def calculate_area(self): print("Area of Rectangle :", self.length * self.width) # function def area(shape): # call action shape.calculate_area() # create object cir = Circle(5) rect = Rectangle(10, 5) # call common function area(cir) area(rect)
Area of circle : 78.5 Area of Rectangle : 50
Inheritance In Python
In an Object-oriented programming language, inheritance is an important aspect. 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.
class BaseClass: Body of base class class DerivedClass(BaseClass): Body of derived class
Example: Use of Inheritance in Python
in the below example, From a vehicle class, we are creating a Car class. We don't need to define common attributes and methods again in Car class. We only need to add those attributes and methods which are specific to the Car.
In inheritance, the child class acquires all the data members, properties, and functions of the parent class. Also, a child class can customize any of the parent class methods.
# Base class class Vehicle: def __init__(self, name, color, price): self.name = name self.color = color self.price = price def info(self): print(self.name, self.color, self.price) # Child class class Car(Vehicle): def change_gear(self, no): print(self.name, 'change gear to number', no) # Create object of Car car = Car('BMW X1', 'Black', 35000) car.info() car.change_gear(5)
BMW X1 Black 35000 BMW X1 change gear to number 5
All Python OOP tutorials: