OOPs Concepts in Python | Set-2

Published on:
October 21, 2022

In the previous article (OOPs Concepts in Python | Set-1), we explained classes, objects, and methods in Python.

Now in this article, we will explain further principles of OOP concepts in Python:  Inheritance, Encapsulation, Polymorphism, and Data abstraction. 

These are briefly explained below as follows.

(1). Inheritance

As you know a child can inherit some or the other characteristics from its parents. The child may have hereditary traits (surname, genes, DNA) and/or actions (or manner - walk (), read (), talk ()). So, inheritance is a real-world concept in OOPs.

In OOPs, the "child classes" inherit features from their "parent classes". These attributes are "properties" and "methods". The process of inheriting the properties of the parent class to the child class is known as inheritance. 

Inherited class is known as "Parent class" or “Base class” and Inherits class is known as "Child class" or “Derived class”

Syntax

Consider the following example,

Since we have inherited the parent class's properties (name, age, gender) and method (introduction), so, if we create a child object. For instance, it can also access all the properties (name, age, gender) and method (introduction) of the parent class from the child class. This is because of the inheritance properties of OOP in Python.

But we cannot access the property or methods of the parent class in the parent class. Here child class has the method "school," which cannot be accessed in the parent class. Otherwise, an error will occur if you try to access the child class property or method in the parent class.

But we can access it in its own way only in child class.

Consider the following example,

It will throw an error - 'Parent' object has no attribute 'school', because we have created an object x using Parent class and attribute “school” is an attribute of “Child class” only, so we can not access it. Hence, we get an error.

Super()

It is an inheritance-related function that refers to the parent class. We use it to find a method with a particular name in an object Superclass.

Syntax

super().method_name()

Consider the following example,

We run a business

Therefore, it will be called even if there is a method with the same name in the subclass. If we do not use "Super()" in the attribute or methods of the child class, the output of the child class will take precedence in case of a conflict of the same name. "Super()" ensures that the properties will only be from the parent and not the child.

There are various types of Inheritance : Single, Multiple, Multi-level, Hybrid, and Hierarchical inheritance.

(2). Polymorphism

As the name suggests, 'poly' means multiple and 'morph' means form. So, polymorphism means something that has many forms or can have many behaviors depending on the situation.

In OOP, polymorphism means functions with the same name but different functionalities or similar function names but different function signatures (parameters passed to the function). 

A child class inherits all the properties and methods from its parent class. Plus it can add its own properties and methods. There are many ways in which we can use polymorphism in Python.

Example

len() is an example of an inbuilt polymorphic function. It can calculate the length of different types like string, list, tuple or dictionary, it will just calculate the result and return. 

Consider the following example,

There is another example of polymorphism with the '+' addition operator.

It (‘+’ operator) can perform different operations for distinct data types. 

Polymorphism with Class Methods

Polymorphism with Function and Objects. Consider the following example,

Consider another example,

Here, a variable "person" is used to iterate over the instances of both "Boy" and "Girl". So, it is used to represent the behavior (intro() and hobby()) of the boy as well as the girl. Therefore, it follows the rules of polymorphism.

Polymorphism with Inheritance

Now we will see Polymorphism with Inheritance. We can modify a method in a child class that it inherits from the parent class, and it can add its own implementation to the method. This process is known as method overriding. 

Note that Python supports method overriding but does not support method overloading. We can overload the methods but use only the latest defined method.

Consider the following example,

(3). Encapsulation

Like medicine capsules, where all medicines are enclosed inside a capsule cover, similarly, in programming, variables and methods are enclosed inside a capsule called a 'class'.

Encapsulation is one of the concept of OOPS in Python. Encapsulation is a process of binding data and associated methods (behavior) together into a single entity. Encapsulation is used to hide the value or state of a structured data object inside a class. This prevents them from being accessed by other classes.

Encapsulation ensures security and hides the data from the access of outsiders. It protects its content from unwanted access by clients or any unauthorized person by encapsulating it.

Getters and Setters

Since we use encapsulation to hide the data. So, to do this, we use getter which provides access to read data. The setter provides access to write or update data on it. By avoiding them, they can be saved.

Consider the following example,

In the above example, we have used getters and setters to read and write on the data. Now we can use these setter and getter to access and read any value, otherwise, we cannot get or modify any value directly. It helps in enhancing the security of the data. To get and set we don't need to know the whole class, only these two. We may also promote "access modifiers" to enhance the greater security of the data.

Access Modifiers

We use access modifiers to limit access to variables and methods of a class. There are three types of access modifiers - private, public and protected.

  1. Private Member: Accessible within the class
  2. Protected Member: Accessible within the class and its sub-classes
  3. Public Member: Accessible anywhere from otside oclass.

Class member access specifier

Access from own class

Accessible from derived class

Accessible from object

1. Private member

Yes

No

No

2. Protected member

Yes

Yes

No

3. Public member

Yes

Yes

Yes

In Python, we don't write the access modifier name, but we use -

  • Single underscore _ represents Protected class. 
  • Double underscore __ represents Private class.

Since public is always there by default, so there is no need to represent by special symbol like private and protected case.

Consider the following example,

As we have defined emp "salary" as private attribute so we cannot access it outside this class. However, we can access the employee's salary by calling getSalary() created in our Employee class. This is the significance of getters and setters with access modifiers.

Modified above example,

There is no error because we have used getter method to access a private member. It provides safety for other data while accessing member attributes.

If we declare the class as public then we can access the private members of this public class." Mangling is another type of getter access.

(4). Abstraction

Like a virtual keyboard, we can only see the keyboard and don't care about its inner workings, similarly, in abstraction, it shows functionality, while hiding all implementation or internal details.

The main goal of abstraction is to hide background details or any unnecessary implementations about the data so that users can see only essential information. It helps in handling the complexity of the code.

Abstraction can be achieved using abstract classes in Python. An abstract class can contain one or more abstract methods. These abstract classes can be inherited by any subclass and act like blueprints for other classes. The “abc” module is used for abstraction in Python. “ABC” stands for Abstract Base Class. “ABC” module provides base definition.

Syntax

Consider following example,

Person(abc) is abstract class here because abstract class inherits "abc". The class Person (ABC) has a gender() abstract method that has no definition.

The other subclasses of the super (or base) class "Person" are "Male", "Female" and "Other". These inherit the "Person" class and provide their own implementation for the abstract method.

Note that abstract classes cannot be instantiated, you cannot create their objects. Also, abstract classes can have both types of methods: normal and abstract method.

We have explained the various important points of OOPs in Python. OOPs has various benefits, such as effective problem solving, flexibility through polymorphism, reducing high complexity of code through abstraction, high security through encapsulation, code reuse through inheritance etc.


Similar Posts