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).
In this lesson, you will learn about OOP (Object Oriented Programming) in Python. OOP concepts include object, classes, constructor and encapsulation, polymorphism, and inheritance.
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
Table of contents
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, developing a building according to the building plan. The plan contains all dimensions and structure. Based on these descriptions, we can construct a building. Here, a building is an object.
Class to represent the properties (attribute) and action (behavior) of the object. Properties represent variables, and actions are represented by the methods. Hence class contains both variables and methods.
In Python, create a class by using the keyword
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 component statements, variables, methods, functions, attributes.
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.
We can create any number of objects for class. Below is the syntax used to create an object.
reference_variable = classname()
Example: Creating Class and Object in Python
class Student: """This is student class with data""" # A sample method def learn(self): print("Learning Python Programming") # creating object stud = Student() # Calling method stud.learn() # Output: Learning Python Programming
In the above example, we created a
Class with the name
Student. Also, we created an object
With help of class objects, we can access class methods. Here we accessing the
learn() method by using the
Instance Variables and Methods
If the value of a variable varies from object to object, then such variables are called instance variables. For every object, a separate copy of the instance variable will be created.
When we create classes in Python, instance methods are used regularly. we need to create an object to execute the block of code or action defined in the instance method.
We can access the instance variable and methods using the object. Use dot (
.) operator to access instance variables and methods.
In Python, working with an instance variable and method, we use the
self keyword. When we use the
self keyword as a parameter to a method or with a variable name is called the instance itself.
Note: Instance variables are used within the instance method
class Student: def __init__(self, name, percentage): self.name = name self.percentage = percentage def show(self): print("Name is:", self.name, "and percentage is:", self.percentage) stud = Student("Jessa", 80) stud.show() # Output Name is: Jessa and percentage is: 80
In the above example,
percentage are instance variables, and these variables get initialized when we create an object for the
Student class. Here, the
show() method is an instance method. If we want to call that method we need to create an object of the class.
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.
We have two types of constructors in Python.
- Non-parameterized: The constructors in Python which have no parameter is known as a 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.
- Parameterized Constructor: The constructor with parameters is known as a parameterized constructor. The parameterized constructor has multiple parameters along with the
Example: Constructor without parameters (Non-parameterized)
class Test: # Constructor - non parameterized def __init__(self): print("This is non parametrized constructor") def show(self, name): print("Hello", name) # creating object of the class t = Test() # Output:This is non parametrized constructor # calling the instance method t.show("Jessa") # Output Hello Jessa
Example: Constructor with parameters
class Fruit: # parameterized constructor def __init__(self, name, color): print("This is parametrized constructor") self.name = name self.color = color def show(self): print("Fruit is", self.name, "and Color is", self.color) # creating object of the class # this will invoke parameterized constructor obj = Fruit("Apple", "red") # Output This is parametrized constructor # calling the instance method using the object obj.show() # Output Fruit is Apple and Color is red
In the above example, we create a parameterized constructor with parameters
color. When we create an object of
Test class called
obj, the parameterized constructor will be executed automatically.
self is used to represent the instance of the class. It is the default variable that is always pointing to the current object.
self, we can access the instance variable and instance method of the object. While defining constructor and instance method, the
self is their first parameter.
It’s not required the first parameter named to be
self, we can give any name whatever we like, but it has to be the first parameter of any function in the class.
class Employee: def __init__(self, id, name): # instance variable self.id = id self.name = name # instance method def info(self): print("Employee ID is ", self.id, "and name is", self.name) # instance method def department(self): print("Employee of IT department") emp = Employee(10112, "Harry", ) emp.info() # Output Employee ID is 10112 and name is Harry emp.department() # Output Employee of IT department
In the above example, all methods including
__init__ have a
self parameter. We created two instance variables
name. Then we create an object of a class
emp and accessed instance methods of the class called
A class variable is a variable that is declared inside of class, but outside of any class method, they are not defined inside any class method.
Only one copy of the class variable will be created and shared by all objects of a class. Class variables are not used as frequently as instance variables.
A class variable alone looks like this:
class Student: # class Variable Subject = "Python"
We can access class variables either by class name or object reference but recommended to use the class name.
class Employee: depatment = "IT" def show(self): print("Department is ", self.depatment) emp = Employee() emp.show() # Output Department is IT print("class variable:", Employee.depatment) # Output IT
In the above example, we declare a
Class variable called the
department. Also, we created an instance of
Class and print class variable using a class name with dot notation.
Every object has properties with it. In other words, we can say that object property is an association between name and value.
For example, a car is an object, and its properties are car color, sunroof, price, manufacture, model, engine, and so on. Here, color is the name and red is the value.
Modify Object Properties
Every object has properties associated with them. We can set or modify the object’s properties after object initialization by calling the property directly using the dot operator.
Obj.PROPERTY = value
class Fruit: def __init__(self, name, color): self.name = name self.color = color def show(self): print("Fruit is", self.name, "and Color is", self.color) # creating object of the class obj = Fruit("Apple", "red") # Modifying Object Properties obj.name = "strawberry" # calling the instance method using the object obj obj.show() # Output Fruit is strawberry and Color is red
Delete object properties
We can delete the object property by using the
del keyword. After deleting it, if we try to access it, we will get an error.
class Fruit: def __init__(self, name, color): self.name = name self.color = color def show(self): print("Fruit is", self.name, "and Color is", self.color) # creating object of the class obj = Fruit("Apple", "red") # Deleting Object Properties del obj.name # Accessing object properties after deleting print(obj.name) # Output: AttributeError: 'Fruit' object has no attribute 'name'
In the above example, As we can see, the attribute name has been deleted when we try to print or access that attribute gets an error message.
In Python, we can also delete the object by using a
del keyword. An object can be anything like, class object,
Example : Deleteing object
class Employee: depatment = "IT" def show(self): print("Department is ", self.depatment) emp = Employee() emp.show() # delete object del emp # Accessing after delete object emp.show() # Output : NameError: name 'emp' is not defined
In the above example, we create the object
emp of the class
Employee. After that, using the
del keyword, we deleted that object.
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.
In Python, we do not have access modifiers directly, such as public, private, and protected. But we can achieve encapsulation by using single prefix underscore and double underscore to control access of variable and method within the Python program.
See the following example where we have implement encapsulation.
class Employee: def __init__(self, name, salary): self.name = name self.__salary = salary def show(self): print("Name is ", self.name, "and salary is", self.__salary) # Outside class E = Employee("Jessa", 40000) E.PrintName() print(E.name) print(E.PrintName()) print(E.__salary) # 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 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.
In Python, polymorphism allows us to define the child class methods with the same name as defined in the parent class.
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) cir = Circle(5) rect = Rectangle(10, 5) cir.calculate_area() # Output Area of circle : 78.5 rect.calculate_area() # Output Area od Rectangle : 50
In the above example, we created two classes called
Rectangle. In both classes, we created the same method with the name
calculate_area. This method acts differently in both classes. In the case of the
Circle class, it calculates the area of the circle, whereas, in the case of a
Rectangle class, it calculates the area of a rectangle.
In an Object-oriented programming language, inheritance is an important aspect. The main purpose of inheritance is the reusability of code because we can use the existing class to create a new class instead of creating it from scratch.
In Python, inheritance is the process of inheriting the properties of the parent class into a child class.
In inheritance, the child class acquires and access all the data members, properties, and functions from the parent class. Also, a child class can also provide its specific implementation to the functions of the parent class.
Use of inheritance
To create classes that are built upon existing classes called reusability. So, we do not have to write the same code again and again.
class BaseClass: Body of base class class DerivedClass(BaseClass): Body of derived class
class ClassOne: def func1(self): print('We are in Base class') class ClassTwo(ClassOne): def func2(self): print('We are in child class') obj = ClassTwo() obj.func1() obj.func2()
We are in base class We are in child class
In the above example, we create two classes called
ClassTwo is derived from
ClassOne that is the base class. While calling functions, create an object of child class called
obj and called with the help of that object, that is,