Object-Oriented Programming with Python

Object-Oriented Programming with Python

17 mins read1.4K Views Comment
Updated on Jan 19, 2023 14:27 IST

A good understanding of OOPs concepts can help you make your Python programming journey smoother. In this article, we will explore the basics of object-oriented programming in Python.

2022_01_Object-Oriented-Programming-in-Python.jpg

Python is a high-level, interpreted programming language that supports object-oriented programming paradigm. The object-oriented programming features in Python make it easier for programmers to model their code appropriately and to build programs of increasing complexity and modularity. So, it is critical to have a strong understanding of OOPs concepts to make your Python programming journey smoother. This article brings to you the basics of object-oriented programming in Python. The topics covered in this article are:

Explore free Python courses

  1. Introduction to Object-Oriented Programming in Python
  2. Objects and Classes
  3. Inheritance
  4. Polymorphism
  5. Encapsulation
  6. Data Abstraction
  7. Conclusion

Explore- Python Online Courses & Certifications

Introduction to Object-oriented Programming in Python

The concept of object-oriented programming (OOPs) gained momentum in the 1970s and is by far the most functional and imperative computer programming paradigm today. It provides a natural way of modeling real-world complex problems by use of pre-defined programming modular units, generally referred to as objects. Some of the most widely used programming languages that support object-oriented programming today are Java, Python, C++, C#, Ruby and others.

Python fully supports the OOPs paradigm. In fact, almost everything from strings to lists, functions, classes, modules, and dictionaries that we use are actually objects. So, what exactly is an object?

Objects in Python

Objects are key to understanding object-oriented programming. Formally, you can think of an object as a collection of data and associated behaviors. If you look around, you will find many real-life examples of objects.

Must Read: Data Type in Python

Taking a dog as an example of an object, it has characteristics such as name, colour, breed, and behaviors such as wagging its tail, barking, fetching a ball, etc. Similarly, if we consider a car, it has characteristics like the model, color, version, registration number, etc. It has behaviors like changing gear, pressing the accelerator, applying the brakes, etc. Here’s a simple example of an object of a dog named Toby.

 
\n \n \n <span style="color: #808080; font-style: italic;">\n \n \n #Example 1\n \n \n
\n \n \n <span style="color: #ff7700; font-weight: bold;">\n \n \n def toby_dog\n \n \n <span style="color: black;">\n \n \n (\n \n \n <span style="color: black;">\n \n \n ):\n \n \n
name \n \n \n <span style="color: #66cc66;">\n = \n <span style="color: #483d8b;">\n "Toby" \n
age \n <span style="color: #66cc66;">\n = \n <span style="color: #ff4500;">\n 4 \n
breed \n <span style="color: #66cc66;">\n = \n <span style="color: #483d8b;">\n "Bull Dog" \n
\n <span style="color: #ff7700; font-weight: bold;">\n print \n <span style="color: black;">\n ( \n <span style="color: #483d8b;">\n "The name is" \n <span style="color: #66cc66;">\n , name \n <span style="color: #66cc66;">\n , \n <span style="color: #483d8b;">\n "of age" \n <span style="color: #66cc66;">\n , age \n <span style="color: #66cc66;">\n , \n <span style="color: #483d8b;">\n "and of breed" \n <span style="color: #66cc66;">\n , breed \n <span style="color: black;">\n ) \n
\n
toby_dog \n <span style="color: black;">\n ( \n <span style="color: black;">\n ) \n </span style="color: black;"> \n </span style="color: black;"> \n </span style="color: black;"> \n </span style="color: #66cc66;"> \n </span style="color: #483d8b;"> \n </span style="color: #66cc66;"> \n </span style="color: #66cc66;"> \n </span style="color: #483d8b;"> \n </span style="color: #66cc66;"> \n </span style="color: #66cc66;"> \n </span style="color: #483d8b;"> \n </span style="color: black;"> \n </span style="color: #ff7700; font-weight: bold;"> \n </span style="color: #483d8b;"> \n </span style="color: #66cc66;"> \n </span style="color: #ff4500;"> \n </span style="color: #66cc66;"> \n </span style="color: #483d8b;"> \n </span style="color: #66cc66;">\n \n \n </span style="color: black;">\n \n \n </span style="color: black;">\n \n \n </span style="color: #ff7700; font-weight: bold;">\n \n \n </span style="color: #808080; font-style: italic;">
Copy code

Let’s make this more interesting.

You can represent any object in terms of attributes (e.g name, brand, color, etc.) and behaviors (e.g moving, eating, communicating, calculating, etc.). Now, what if you have different types of objects? Let’s pretend we’re doing an inventory application for a pet sanctuary. Now, we have different kinds of objects: cats, dogs, hamsters, rabbits, etc. It would be meaningless to write a unique code for each dog, each cat, etc, right? This is where the concept of classes comes into the picture.

Read more- What are the Top 10 Python Applications in Real-World?

Recommended online courses

Best-suited Python courses for you

Learn Python with these high-rated online courses

Free
6 weeks
– / –
2 weeks
– / –
16 weeks
1.7 K
3 months
– / –
– / –
4.24 K
2 weeks
3 K
3 weeks
– / –
4 months

Objects and Classes

Classes are Python’s main object-oriented programming (OOP) tool. They are like blueprints for creating an object and basically describe an object. Let’s try to decipher this with an interesting example.

Ever heard of the popular Spanish crime thriller series La Casa de Papel (also known as Money Heist)? The show follows a professor and his band of robbers as they indulge in nerve-wracking heists with their signature red jumpsuits and Dalí masks. It’s hard to imagine a thriller without its main characters.

Coming to the point, you can consider each of these robbers an individual object, but all of them have the attributes and behaviors associated with one class, which is: the general calls of robbers. Just like someone needs to build a car using the blueprint of the engineering designs before you can use it, you need to have a class before you can create an object. The process of doing this is known as instantiation and the object is then referred to as an instance of a class.

2022_01_Instance.jpg

To create your own custom object in Python, you first need to define a class using the keyword class as shown below. We will start with the simplest class and then gradually build it up to do something useful.

 
\n \n \n <span style="color: #808080; font-style: italic;">\n \n \n #Example 2\n \n \n
\n \n \n <span style="color: #ff7700; font-weight: bold;">\n \n \n class Robbers:\n \n \n
\n \n \n <span style="color: #ff7700; font-weight: bold;">\n \n \n pass\n \n \n
\n \n \n
\n \n \n <span style="color: #ff7700; font-weight: bold;">\n \n \n print\n \n \n <span style="color: black;">\n (Robbers.__class__ \n <span style="color: black;">\n ) \n
\n <span style="color: #ff7700; font-weight: bold;">\n print \n <span style="color: black;">\n (Robbers.__class__.__base__ \n <span style="color: black;">\n ) \n </span style="color: black;"> \n </span style="color: black;"> \n </span style="color: #ff7700; font-weight: bold;"> \n </span style="color: black;"> \n </span style="color: black;">\n \n \n </span style="color: #ff7700; font-weight: bold;">\n \n \n </span style="color: #ff7700; font-weight: bold;">\n \n \n </span style="color: #ff7700; font-weight: bold;">\n \n \n </span style="color: #808080; font-style: italic;">
Copy code

As you can see, the class is an object of the class named type and the base class for our class is an object. You can now create multiple objects of type Robber using this class. You can do that by calling the class name as though it were a function.

Nairobi = Robbers()

This creates an individual object from the Robbers class and assigns it to the name Nairobi. Since the class Robbers is empty, the object Nairobi that we create from it just sits there idly and does nothing. Now, let us go one step ahead and implement a special object initialization method in Python __init__:

 
\n \n \n <span style="color: #808080; font-style: italic;">\n \n \n #Example 3\n \n \n
\n \n \n <span style="color: #ff7700; font-weight: bold;">\n \n \n class Robbers:\n \n \n
\n \n \n <span style="color: #ff7700; font-weight: bold;">\n \n \n def \n \n \n <span style="color: #0000cd;">\n \n \n __init__\n \n \n <span style="color: black;">\n ( \n <span style="color: #008000;">\n self \n <span style="color: black;">\n ): \n
\n <span style="color: #ff7700; font-weight: bold;">\n pass \n </span style="color: #ff7700; font-weight: bold;"> \n </span style="color: black;"> \n </span style="color: #008000;"> \n </span style="color: black;">\n \n \n </span style="color: #0000cd;">\n \n \n </span style="color: #ff7700; font-weight: bold;">\n \n \n </span style="color: #ff7700; font-weight: bold;">\n \n \n </span style="color: #808080; font-style: italic;">
Copy code

While it’s not explicitly needed, we are basically initializing an object from its class definition by implementing the __init__() method. Also, the argument self means that it refers to the individual object itself (the one that you are working with at that point of time). So, when you define __init__() method, its first parameter should be self.

That’s simple enough, but what are these data and behaviors associated with the objects?

Attributes

Data or attributes typically represent the specific characteristics of a certain object. When you create a class, you can define a set of characteristics that are shared by the objects of that class. Attributes are often referred to as members or properties. Also, each object of a class can have different or the same values for the given characteristics. In our Money Heist example, you might want to know the actual name of the robber, his/her alias, gender, the weapon he/she uses, among other things.

 
\n \n \n <span style="color: #808080; font-style: italic;">\n \n \n #Example 4\n \n \n
\n \n \n <span style="color: #ff7700; font-weight: bold;">\n \n \n class Robbers:\n \n \n
\n \n \n <span style="color: #ff7700; font-weight: bold;">\n \n \n def \n \n \n <span style="color: #0000cd;">\n \n \n __init__\n \n \n <span style="color: black;">\n ( \n <span style="color: #008000;">\n self \n <span style="color: #66cc66;">\n , name \n <span style="color: #66cc66;">\n , alias \n <span style="color: #66cc66;">\n , age \n <span style="color: #66cc66;">\n , gender \n <span style="color: #66cc66;">\n , weapon \n <span style="color: black;">\n ): \n
\n <span style="color: #008000;">\n self. \n <span style="color: black;">\n name \n <span style="color: #66cc66;">\n = name \n
\n <span style="color: #008000;">\n self. \n <span style="color: black;">\n alias \n <span style="color: #66cc66;">\n = alias \n
\n <span style="color: #008000;">\n self. \n <span style="color: black;">\n age \n <span style="color: #66cc66;">\n = age \n
\n <span style="color: #008000;">\n self. \n <span style="color: black;">\n gender \n <span style="color: #66cc66;">\n = gender \n
\n <span style="color: #008000;">\n self. \n <span style="color: black;">\n weapon \n <span style="color: #66cc66;">\n = weapon \n
\n
tokyo \n <span style="color: #66cc66;">\n = Robbers \n <span style="color: black;">\n ( \n <span style="color: #483d8b;">\n 'Silene Oliveria' \n <span style="color: #66cc66;">\n , \n <span style="color: #483d8b;">\n 'Tokyo' \n <span style="color: #66cc66;">\n , \n <span style="color: #ff4500;">\n 30 \n <span style="color: #66cc66;">\n , \n <span style="color: #483d8b;">\n 'Female' \n <span style="color: #66cc66;">\n , \n <span style="color: #483d8b;">\n 'Heckler & Koch MP5' \n <span style="color: black;">\n ) \n
\n <span style="color: #ff7700; font-weight: bold;">\n print \n <span style="color: black;">\n ( \n <span style="color: #483d8b;">\n "Character:" \n <span style="color: #66cc66;">\n , tokyo. \n <span style="color: black;">\n name \n <span style="color: #66cc66;">\n , \n <span style="color: #483d8b;">\n " \n <span style="color: #000099; font-weight: bold;">\n Alias:" \n <span style="color: #66cc66;">\n , tokyo. \n <span style="color: black;">\n alias \n <span style="color: #66cc66;">\n , \n <span style="color: #483d8b;">\n " \n <span style="color: #000099; font-weight: bold;">\n Age:" \n <span style="color: #66cc66;">\n , tokyo. \n <span style="color: black;">\n age \n <span style="color: #66cc66;">\n , \n <span style="color: #483d8b;">\n " \n <span style="color: #000099; font-weight: bold;">\n Weapon:" \n <span style="color: #66cc66;">\n , tokyo. \n <span style="color: black;">\n weapon \n <span style="color: black;">\n ) \n </span style="color: black;"> \n </span style="color: black;"> \n </span style="color: #66cc66;"> \n </span style="color: #000099; font-weight: bold;"> \n </span style="color: #483d8b;"> \n </span style="color: #66cc66;"> \n </span style="color: black;"> \n </span style="color: #66cc66;"> \n </span style="color: #000099; font-weight: bold;"> \n </span style="color: #483d8b;"> \n </span style="color: #66cc66;"> \n </span style="color: black;"> \n </span style="color: #66cc66;"> \n </span style="color: #000099; font-weight: bold;"> \n </span style="color: #483d8b;"> \n </span style="color: #66cc66;"> \n </span style="color: black;"> \n </span style="color: #66cc66;"> \n </span style="color: #483d8b;"> \n </span style="color: black;"> \n </span style="color: #ff7700; font-weight: bold;"> \n </span style="color: black;"> \n </span style="color: #483d8b;"> \n </span style="color: #66cc66;"> \n </span style="color: #483d8b;"> \n </span style="color: #66cc66;"> \n </span style="color: #ff4500;"> \n </span style="color: #66cc66;"> \n </span style="color: #483d8b;"> \n </span style="color: #66cc66;"> \n </span style="color: #483d8b;"> \n </span style="color: black;"> \n </span style="color: #66cc66;"> \n </span style="color: #66cc66;"> \n </span style="color: black;"> \n </span style="color: #008000;"> \n </span style="color: #66cc66;"> \n </span style="color: black;"> \n </span style="color: #008000;"> \n </span style="color: #66cc66;"> \n </span style="color: black;"> \n </span style="color: #008000;"> \n </span style="color: #66cc66;"> \n </span style="color: black;"> \n </span style="color: #008000;"> \n </span style="color: #66cc66;"> \n </span style="color: black;"> \n </span style="color: #008000;"> \n </span style="color: black;"> \n </span style="color: #66cc66;"> \n </span style="color: #66cc66;"> \n </span style="color: #66cc66;"> \n </span style="color: #66cc66;"> \n </span style="color: #66cc66;"> \n </span style="color: #008000;"> \n </span style="color: black;">\n \n \n </span style="color: #0000cd;">\n \n \n </span style="color: #ff7700; font-weight: bold;">\n \n \n </span style="color: #ff7700; font-weight: bold;">\n \n \n </span style="color: #808080; font-style: italic;">
Copy code

Each object is associated with specific behaviors, but what exactly do we mean by that?

Methods

A method basically is a function that is associated with a particular class. They are basically actions that occur on an object. Methods are defined inside a class to make the relationship between them explicit. In the example that we are working on, the class Robbers can have a method called personality, which gives detailed personality descriptions of a robber. Or, another method that displays the complex relationships of each robber, or a method that calculates the age of the robber given the birth date.

 
\n \n \n <span style="color: #808080; font-style: italic;">\n \n \n #Example 5\n \n \n
\n \n \n <span style="color: #ff7700; font-weight: bold;">\n \n \n import \n \n \n <span style="color: #dc143c;">\n \n \n datetime\n \n \n
\n \n \n <span style="color: #ff7700; font-weight: bold;">\n \n \n from \n \n \n <span style="color: #dc143c;">\n datetime \n <span style="color: #ff7700; font-weight: bold;">\n import date \n
\n
\n <span style="color: #ff7700; font-weight: bold;">\n class Robbers: \n
\n <span style="color: #ff7700; font-weight: bold;">\n def \n <span style="color: #0000cd;">\n __init__ \n <span style="color: black;">\n ( \n <span style="color: #008000;">\n self \n <span style="color: #66cc66;">\n , name \n <span style="color: #66cc66;">\n , alias \n <span style="color: #66cc66;">\n , gender \n <span style="color: #66cc66;">\n , weapon \n <span style="color: #66cc66;">\n , bdate \n <span style="color: black;">\n ): \n
\n <span style="color: #008000;">\n self. \n <span style="color: black;">\n name \n <span style="color: #66cc66;">\n = name \n
\n <span style="color: #008000;">\n self. \n <span style="color: black;">\n alias \n <span style="color: #66cc66;">\n = alias \n
\n <span style="color: #008000;">\n self. \n <span style="color: black;">\n gender \n <span style="color: #66cc66;">\n = gender \n
\n <span style="color: #008000;">\n self. \n <span style="color: black;">\n weapon \n <span style="color: #66cc66;">\n = weapon \n
\n <span style="color: #008000;">\n self. \n <span style="color: black;">\n bdate \n <span style="color: #66cc66;">\n = bdate \n
\n
\n <span style="color: #ff7700; font-weight: bold;">\n def calculateAge \n <span style="color: black;">\n ( \n <span style="color: #008000;">\n self \n <span style="color: #66cc66;">\n , bdate \n <span style="color: black;">\n ): \n
today \n <span style="color: #66cc66;">\n = date. \n <span style="color: black;">\n today \n <span style="color: black;">\n ( \n <span style="color: black;">\n ) \n
age \n <span style="color: #66cc66;">\n = today. \n <span style="color: black;">\n year - bdate. \n <span style="color: black;">\n year - \n <span style="color: black;">\n ( \n <span style="color: black;">\n (today. \n <span style="color: black;">\n month \n <span style="color: #66cc66;">\n , today. \n <span style="color: black;">\n day \n <span style="color: black;">\n ) \n <span style="color: #66cc66;">\n < \n <span style="color: black;">\n (bdate. \n <span style="color: black;">\n month \n <span style="color: #66cc66;">\n , bdate. \n <span style="color: black;">\n day \n <span style="color: black;">\n ) \n <span style="color: black;">\n ) \n
\n <span style="color: #ff7700; font-weight: bold;">\n return age \n
\n
\n <span style="color: #ff7700; font-weight: bold;">\n def personality \n <span style="color: black;">\n ( \n <span style="color: #008000;">\n self \n <span style="color: #66cc66;">\n , i \n <span style="color: black;">\n ): \n
switcher \n <span style="color: #66cc66;">\n = \n <span style="color: black;">\n { \n
\n <span style="color: #483d8b;">\n 'tokyo': \n <span style="color: #483d8b;">\n 'Tokyo is a strong female lead and a free soul' \n <span style="color: #66cc66;">\n , \n
\n <span style="color: #483d8b;">\n 'berlin': \n <span style="color: #483d8b;">\n 'Berlin can be considered cold, hypnotic, sophisticated with high observational skills' \n <span style="color: #66cc66;">\n , \n
\n <span style="color: #483d8b;">\n 'nairobi': \n <span style="color: #483d8b;">\n 'A level-headed female focused accomplishing the job' \n
\n <span style="color: black;">\n } \n
\n <span style="color: #ff7700; font-weight: bold;">\n return switcher. \n <span style="color: black;">\n get \n <span style="color: black;">\n (i \n <span style="color: #66cc66;">\n , \n <span style="color: #483d8b;">\n "Invalid character" \n <span style="color: black;">\n ) \n
\n
\n
Berlin \n <span style="color: #66cc66;">\n = Robbers \n <span style="color: black;">\n ( \n <span style="color: #483d8b;">\n 'Andrés de Fonollosa' \n <span style="color: #66cc66;">\n , \n <span style="color: #483d8b;">\n 'Berlin' \n <span style="color: #66cc66;">\n , \n <span style="color: #483d8b;">\n 'Male' \n <span style="color: #66cc66;">\n , \n <span style="color: #483d8b;">\n 'M16, M1911' \n <span style="color: #66cc66;">\n , \n <span style="color: #483d8b;">\n '1978-07-08' \n <span style="color: black;">\n ) \n
dob \n <span style="color: #66cc66;">\n = \n <span style="color: #dc143c;">\n datetime. \n <span style="color: #dc143c;">\n datetime. \n <span style="color: black;">\n strptime \n <span style="color: black;">\n (Berlin. \n <span style="color: black;">\n bdate \n <span style="color: #66cc66;">\n , \n <span style="color: #483d8b;">\n '%Y-%m-%d' \n <span style="color: black;">\n ) \n
\n <span style="color: #ff7700; font-weight: bold;">\n print \n <span style="color: black;">\n ( \n <span style="color: #483d8b;">\n "Character:" \n <span style="color: #66cc66;">\n , Berlin. \n <span style="color: black;">\n name \n <span style="color: #66cc66;">\n , \n <span style="color: #483d8b;">\n " \n <span style="color: #000099; font-weight: bold;">\n Alias:" \n <span style="color: #66cc66;">\n , Berlin. \n <span style="color: black;">\n alias \n <span style="color: #66cc66;">\n , \n <span style="color: #483d8b;">\n " \n <span style="color: #000099; font-weight: bold;">\n Age:" \n <span style="color: #66cc66;">\n , Berlin. \n <span style="color: black;">\n calculateAge \n <span style="color: black;">\n (dob \n <span style="color: black;">\n ) \n <span style="color: #66cc66;">\n , \n <span style="color: #483d8b;">\n " \n <span style="color: #000099; font-weight: bold;">\n Weapon:" \n <span style="color: #66cc66;">\n , Berlin. \n <span style="color: black;">\n weapon \n <span style="color: black;">\n ) \n
\n <span style="color: #ff7700; font-weight: bold;">\n print \n <span style="color: black;">\n (Berlin. \n <span style="color: black;">\n personality \n <span style="color: black;">\n ( \n <span style="color: #483d8b;">\n 'berlin' \n <span style="color: black;">\n ) \n <span style="color: black;">\n ) \n
\n <p>Methods are how programmers implement code readability and keep the code encapsulated within the object. Obviously, OOP is much more than code reuse. Let us explore very important design constructs related to object-oriented programming in Python: <strong><em>Inheritanc</em></strong>e, <strong><em>Encapsulation</em></strong>, <strong><em>Abstraction</em></strong>, and <strong><em>Polymorphism</em></strong>.</p> \n <h2 id="inheritance"><strong>Inheritance in Object-Oriented Programming</strong></h2> \n <p>Let’s say you are trying to solve a coding problem, but there is already an existing class that creates objects that do almost what you need. What would you do? If you modify the existing class, it might become more complicated and accidentally you might break existing functionality. Of course, you can create a brand-new class by pasting the code from the existing class and merging your new code. Again, there is a lot of code that you have to maintain.</p> \n <p>The best solution is <strong><em>inheritance</em></strong>, which is creating a new class from an already existing class but with few additions and changes. For example, a child inherits a few of the traits of his/her parents. In turn, the parents might have inherited a few traits from their ancestors. This sort of practice enhances code reuse, i.e. the new class can automatically use all the code from the old class without having to copy any of it. So, you can define what is unique to your new class, and this overrides the behavior of the old class.</p> \n <p>The original class is regressed to as superclass, parent, or base class and the new one is called subclass, child, or derived class. An example would be, you can have a superclass called MoneyHeist_Charecters and use this as a parent class for Robber class, Law Enforcement Officers class. We call this <strong><em>single inheritance</em></strong>. Extending this example further we can also have something as shown below. In <strong><em>multiple inheritance</em></strong>, a subclass can inherit from one or more base classes.</p> \n <div class="photo-widget-full"> \n <div class="figure"> \n <picture> \n <source srcset="https://images.shiksha.com/mediadata/ugcDocuments/images/wordpressImages/2022_01_Multiple-Inheritance_480x360.jpg" media="(max-width: 500px)"> \n <img src="https://images.shiksha.com/mediadata/ugcDocuments/images/wordpressImages/2022_01_Multiple-Inheritance.jpg" alt="2022_01_Multiple-Inheritance.jpg" width="1024" height="620"> \n </picture> \n </div> \n </div> \n <p>In object-oriented lingo, each arrow here represents an <strong><em>is-a</em></strong> relationship.</p> \n
Copy code
python| #Example 6
class Robbers:
   def  __init__ ( self , name , alias , gender , bdate ):
     self. name  = name
     self. alias  = alias
     self. gender  = gender
     self. bdate  = bdate
 
   def personality ( self ):
        print ( "I am one of the Money Heist character" )
 
   def calculateAge ( self , bdate ):
    today  = date. today ( )
    age  = today. year - bdate. year -  ( (today. month , today. day (bdate. month , bdate. day ) )
     return age
 
class Professor (Robbers ):
     def  __init__ ( self , name , alias , gender , bdate , role ):
        super ( ). __init__ (name , alias , gender , bdate )
        self. name  = name +  '"' +  " aka " +  self. alias +  '"'
        self. role  "The master mind of the heist"
 
 
     def personality ( self ):
        print ( self. alias "is an enigmatic charcter, sophisticated but nerdy, charismatic yet shy villain" )
 
class Band_Of_Robbers (Robbers ):
    def  __init__ ( self , name , alias , gender , bdate , role , weapon ):
        super ( ). __init__ (name , alias , gender , bdate )
        self. role  = role
        self. weapon  = weapon
 
    def family ( self , related_to ):
        return related_to
 
    def personality ( self , i ):
     switcher = {
                 'tokyo': "Tokyo is a strong female lead and a free soul" ,
                 'berlin': "Berlin can be considered cold, hypnotic, sophisticated with high observational skills" ,
                 'nairobi':  "A level-headed female focused accomplishing the job"
              }
      return switcher. get (i , "Invalid character" )
 
Berlin  = Robbers ( 'Andrés de Fonollosa' 'Berlin' 'Male' '1978-07-08' )
print ( "Character:" , Berlin. name " Alias:" , Berlin. alias )
Berlin. personality ( )
 
Professor  = Professor ( 'Sergio Marquina' 'The Professor' 'Male' '1980-07-08' '' )
dob  datetime. datetime. strptime (Professor. bdate '%Y-%m-%d' )
print ( " Character:" , Professor. name " Alias:" , Professor. alias " Age:" , Professor. calculateAge (dob ) , " Role:" , Professor. role )
Professor. personality ( )
 
Tokyo  = Band_Of_Robbers ( 'Silene Oliveira' 'Tokyo' 'Female' '1990-07-08' 'Robber' 'Heckler & Koch MP5' )
dob  datetime. datetime. strptime (Professor. bdate '%Y-%m-%d' )
print ( " Character:" , Tokyo. name " Alias:" , Tokyo. alias " Age:" , Tokyo. calculateAge (dob ) , " Role:" , Tokyo. role " Weapon:" , Tokyo. weapon )
Tokyo. personality ( 'tokyo' )
print ( "Related to:" , Tokyo. family ( 'Rio' ) )

The key points that we can infer are:

  • Here, we have 2 subclasses Professor and Band_Of_Robbers that inherit the attributes and methods of the base class Robbers. In addition, they also have their own attributes and methods
  • A child class is simply a specialization of the parent class
  • Both Professor and Band_Of_Robbers override a parent method Personality and create their own version. You can override any method, including __init__(). This is method overriding
  • The class Band_Of_Robbers has a method called family, which is not present in its parent class Robbers
  • You can add or override a method from the parent. What if you want to call the parent version of that method? In such case super() comes to your aid
    • The super() gets the definition of class Pet, parent class
    • The __init__() method automatically takes care of passing the self argument to the superclass. All you need is to give optional arguments if any
  • In the class Band_Of_Robbers, the line self.weapon = weapon and the instance method family is the new code that makes class Band_Of_Robbers different from a Robbers

So, inheritance supports code reusability, by allowing you to create a generic parent class and a more specific child class, which automatically gains access to functionalities of the parent class.

What is Switch Case in Python?
What is Switch Case in Python?
There are no built-in switch case statements in Python. However, Python offers multiple methods to replace the switch case functionality to harness all of the above-stated benefits. Here, we will...read more
Python vs Java: Which is Better to Learn in 2024?
Python vs Java: Which is Better to Learn in 2024?
In the world of programming, Python and Java have long been two of the most popular languages. Both have their strengths and are suited to different tasks, but recent trends...read more
Constructors in Python: Definition, Types, and Rules
Constructors in Python: Definition, Types, and Rules
Constructor in python is a special method that is called when an object is created. The purpose of a python constructor is to assign values to the data members within...read more

Polymorphism in Object-Oriented Programming

Polymorphism basically means designing objects to share behavior. In other words, having many forms. Just like how the character called Raquel Murillo plays the role of a police inspector at the beginning of the series and then becomes a robber.

2022_01_Polymorphism.jpg

Actually, we have implemented in the above example, where both Professor and Band_Of_Robbers override a parent method Personality and create their own version. This is method overriding.

It demonstrates how to use polymorphism with inheritance. Here’s another simple example, which demonstrates how to override a built-in function.

 
\n \n \n <span style="color: #808080; font-style: italic;">\n \n \n #Example 7\n \n \n
\n \n \n <span style="color: #ff7700; font-weight: bold;">\n \n \n class Adopting_Pets:\n \n \n
\n \n \n <span style="color: #ff7700; font-weight: bold;">\n \n \n def \n \n \n <span style="color: #0000cd;">\n \n \n __init__\n \n \n <span style="color: black;">\n ( \n <span style="color: #008000;">\n self \n <span style="color: #66cc66;">\n , pets \n <span style="color: #66cc66;">\n , buyer \n <span style="color: black;">\n ): \n
\n <span style="color: #008000;">\n self. \n <span style="color: black;">\n pets \n <span style="color: #66cc66;">\n = \n <span style="color: #008000;">\n list \n <span style="color: black;">\n (pets \n <span style="color: black;">\n ) \n
\n <span style="color: #008000;">\n self. \n <span style="color: black;">\n buyer \n <span style="color: #66cc66;">\n = buyer \n
\n
\n <span style="color: #ff7700; font-weight: bold;">\n def \n <span style="color: #0000cd;">\n __len__ \n <span style="color: black;">\n ( \n <span style="color: #008000;">\n self \n <span style="color: black;">\n ): \n
\n <span style="color: #ff7700; font-weight: bold;">\n print \n <span style="color: black;">\n ( \n <span style="color: #483d8b;">\n 'Redefine count of pets to adopt by adding the count of accessories' \n <span style="color: black;">\n ) \n
count \n <span style="color: #66cc66;">\n = \n <span style="color: #008000;">\n len \n <span style="color: black;">\n ( \n <span style="color: #008000;">\n self. \n <span style="color: black;">\n pets \n <span style="color: black;">\n ) \n
\n <span style="color: #808080; font-style: italic;">\n # count total items in a different way \n
\n <span style="color: #808080; font-style: italic;">\n # pets plus a basket for each \n
\n <span style="color: #ff7700; font-weight: bold;">\n return count * \n <span style="color: #ff4500;">\n 2 \n
\n
shopping \n <span style="color: #66cc66;">\n = Adopting_Pets \n <span style="color: black;">\n ( \n <span style="color: black;">\n [ \n <span style="color: #483d8b;">\n 'Persian Cat' \n <span style="color: #66cc66;">\n , \n <span style="color: #483d8b;">\n 'Ragdoll Cat' \n <span style="color: black;">\n ] \n <span style="color: #66cc66;">\n , \n <span style="color: #483d8b;">\n 'Maxwell' \n <span style="color: black;">\n ) \n
\n <span style="color: #ff7700; font-weight: bold;">\n print \n <span style="color: black;">\n ( \n <span style="color: #008000;">\n len \n <span style="color: black;">\n (shopping \n <span style="color: black;">\n ) \n <span style="color: black;">\n ) \n </span style="color: black;"> \n </span style="color: black;"> \n </span style="color: black;"> \n </span style="color: #008000;"> \n </span style="color: black;"> \n </span style="color: #ff7700; font-weight: bold;"> \n </span style="color: black;"> \n </span style="color: #483d8b;"> \n </span style="color: #66cc66;"> \n </span style="color: black;"> \n </span style="color: #483d8b;"> \n </span style="color: #66cc66;"> \n </span style="color: #483d8b;"> \n </span style="color: black;"> \n </span style="color: black;"> \n </span style="color: #66cc66;"> \n </span style="color: #ff4500;"> \n </span style="color: #ff7700; font-weight: bold;"> \n </span style="color: #808080; font-style: italic;"> \n </span style="color: #808080; font-style: italic;"> \n </span style="color: black;"> \n </span style="color: black;"> \n </span style="color: #008000;"> \n </span style="color: black;"> \n </span style="color: #008000;"> \n </span style="color: #66cc66;"> \n </span style="color: black;"> \n </span style="color: #483d8b;"> \n </span style="color: black;"> \n </span style="color: #ff7700; font-weight: bold;"> \n </span style="color: black;"> \n </span style="color: #008000;"> \n </span style="color: black;"> \n </span style="color: #0000cd;"> \n </span style="color: #ff7700; font-weight: bold;"> \n </span style="color: #66cc66;"> \n </span style="color: black;"> \n </span style="color: #008000;"> \n </span style="color: black;"> \n </span style="color: black;"> \n </span style="color: #008000;"> \n </span style="color: #66cc66;"> \n </span style="color: black;"> \n </span style="color: #008000;"> \n </span style="color: black;"> \n </span style="color: #66cc66;"> \n </span style="color: #66cc66;"> \n </span style="color: #008000;"> \n </span style="color: black;">\n \n \n </span style="color: #0000cd;">\n \n \n </span style="color: #ff7700; font-weight: bold;">\n \n \n </span style="color: #ff7700; font-weight: bold;">\n \n \n </span style="color: #808080; font-style: italic;">
Copy code

In other languages, we have something called method overloading, the process of calling the same method by passing a different number of parameters in the method call. Based on the number of parameters, the results may vary. Python does not support method overloading. To overcome the above problem, you can use some workaround ways to achieve method overloading. Lastly, we have operator overloading.

Operator Overloading

It means changing the default behavior of an operator based on the operands (or values) that we use. Basically, you can use a single operator for multiple purposes. Here’s a simple example that demonstrates the different uses of + operator.

 
\n \n \n <span style="color: #808080; font-style: italic;">\n \n \n #Example 8\n \n \n
\n \n \n <span style="color: #808080; font-style: italic;">\n \n \n # adding 2 numbers\n \n \n
\n \n \n <span style="color: #ff7700; font-weight: bold;">\n \n \n print\n \n \n <span style="color: black;">\n \n \n (\n \n \n <span style="color: #ff4500;">\n 10 + \n <span style="color: #ff4500;">\n 20 \n <span style="color: black;">\n ) \n
\n
\n <span style="color: #808080; font-style: italic;">\n # concatenating two strings \n
\n <span style="color: #ff7700; font-weight: bold;">\n print \n <span style="color: black;">\n ( \n <span style="color: #483d8b;">\n 'Dean' + \n <span style="color: #483d8b;">\n 'Winchester' \n <span style="color: black;">\n ) \n
\n
\n <span style="color: #808080; font-style: italic;">\n # merging two list \n
\n <span style="color: #ff7700; font-weight: bold;">\n print \n <span style="color: black;">\n ( \n <span style="color: black;">\n [ \n <span style="color: #ff4500;">\n 10 \n <span style="color: #66cc66;">\n , \n <span style="color: #ff4500;">\n 20 \n <span style="color: #66cc66;">\n , \n <span style="color: #ff4500;">\n 30 \n <span style="color: black;">\n ] + \n <span style="color: black;">\n [ \n <span style="color: #483d8b;">\n 'Dean' \n <span style="color: #66cc66;">\n , \n <span style="color: #483d8b;">\n 'Sam' \n <span style="color: #66cc66;">\n , \n <span style="color: #483d8b;">\n 'Jessy' \n <span style="color: black;">\n ] \n <span style="color: black;">\n ) \n
\n
\n <span style="color: #ff7700; font-weight: bold;">\n class Pets \n <span style="color: black;">\n ( \n <span style="color: black;">\n ): \n
\n <span style="color: #ff7700; font-weight: bold;">\n def \n <span style="color: #0000cd;">\n __init__ \n <span style="color: black;">\n ( \n <span style="color: #008000;">\n self \n <span style="color: #66cc66;">\n , pets \n <span style="color: black;">\n ): \n
\n <span style="color: #008000;">\n self. \n <span style="color: black;">\n pets \n <span style="color: #66cc66;">\n = pets \n
\n
\n <span style="color: #808080; font-style: italic;">\n # Overloading + operator with magic method \n
\n <span style="color: #ff7700; font-weight: bold;">\n def \n <span style="color: #0000cd;">\n __add__ \n <span style="color: black;">\n ( \n <span style="color: #008000;">\n self \n <span style="color: #66cc66;">\n , other \n <span style="color: black;">\n ): \n
\n <span style="color: #ff7700; font-weight: bold;">\n return \n <span style="color: #008000;">\n self. \n <span style="color: black;">\n pets + other. \n <span style="color: black;">\n pets \n
\n
\n <span style="color: #808080; font-style: italic;">\n # creating two objects \n
dogs \n <span style="color: #66cc66;">\n = Pets \n <span style="color: black;">\n ( \n <span style="color: #ff4500;">\n 4 \n <span style="color: black;">\n ) \n
cats \n <span style="color: #66cc66;">\n = Pets \n <span style="color: black;">\n ( \n <span style="color: #ff4500;">\n 3 \n <span style="color: black;">\n ) \n
\n
\n <span style="color: #ff7700; font-weight: bold;">\n print \n <span style="color: black;">\n ( \n <span style="color: #483d8b;">\n "Total number of pets adopted is: " \n <span style="color: #66cc66;">\n , dogs + cats \n <span style="color: black;">\n ) \n
\n </span style="color: black;"> \n </span style="color: #66cc66;"> \n </span style="color: #483d8b;"> \n </span style="color: black;"> \n </span style="color: #ff7700; font-weight: bold;"> \n </span style="color: black;"> \n </span style="color: #ff4500;"> \n </span style="color: black;"> \n </span style="color: #66cc66;"> \n </span style="color: black;"> \n </span style="color: #ff4500;"> \n </span style="color: black;"> \n </span style="color: #66cc66;"> \n </span style="color: #808080; font-style: italic;"> \n </span style="color: black;"> \n </span style="color: black;"> \n </span style="color: #008000;"> \n </span style="color: #ff7700; font-weight: bold;"> \n </span style="color: black;"> \n </span style="color: #66cc66;"> \n </span style="color: #008000;"> \n </span style="color: black;"> \n </span style="color: #0000cd;"> \n </span style="color: #ff7700; font-weight: bold;"> \n </span style="color: #808080; font-style: italic;"> \n </span style="color: #66cc66;"> \n </span style="color: black;"> \n </span style="color: #008000;"> \n </span style="color: black;"> \n </span style="color: #66cc66;"> \n </span style="color: #008000;"> \n </span style="color: black;"> \n </span style="color: #0000cd;"> \n </span style="color: #ff7700; font-weight: bold;"> \n </span style="color: black;"> \n </span style="color: black;"> \n </span style="color: #ff7700; font-weight: bold;"> \n </span style="color: black;"> \n </span style="color: black;"> \n </span style="color: #483d8b;"> \n </span style="color: #66cc66;"> \n </span style="color: #483d8b;"> \n </span style="color: #66cc66;"> \n </span style="color: #483d8b;"> \n </span style="color: black;"> \n </span style="color: black;"> \n </span style="color: #ff4500;"> \n </span style="color: #66cc66;"> \n </span style="color: #ff4500;"> \n </span style="color: #66cc66;"> \n </span style="color: #ff4500;"> \n </span style="color: black;"> \n </span style="color: black;"> \n </span style="color: #ff7700; font-weight: bold;"> \n </span style="color: #808080; font-style: italic;"> \n </span style="color: black;"> \n </span style="color: #483d8b;"> \n </span style="color: #483d8b;"> \n </span style="color: black;"> \n </span style="color: #ff7700; font-weight: bold;"> \n </span style="color: #808080; font-style: italic;"> \n </span style="color: black;"> \n </span style="color: #ff4500;"> \n </span style="color: #ff4500;">\n \n \n </span style="color: black;">\n \n \n </span style="color: #ff7700; font-weight: bold;">\n \n \n </span style="color: #808080; font-style: italic;">\n \n \n </span style="color: #808080; font-style: italic;">
Copy code

You can also overload + operator to work with custom objects, such as Pets as shown in the example. You can do so by using the magic method __add__(). The + operator is associated with the function __add__().

Encapsulation in Object-Oriented Programming

Encapsulation simply means containing all the relevant important information inside an object and exposing only selected information to other objects or the outside world. The idea here is to have the capsule separate the class-based interface from the complex implementation details. By doing so you are determining what the public interface of the object will be.

In the Money Heist, the heist can be seen as one big encapsulation. The properties of the heist would be the professor, the band of robbers, the hostages, etc. The related class methods would be taking_hostage(), escape_plan(), etc…

2022_01_Encapsulation.jpg

Let’s consider another simple example to understand the concept, television. Our interface to television is remote. On the remote, you have different buttons (methods) with different functionality, which you use to achieve your goal by implementing a television object. While we are accessing these buttons, we don’t bother about implementation details such as what electric signals are sent for changing the channels or adjusting the volumes, etc.

In Python, the notion of privacy is very simple, “Everything is public”. Conventionally, we can treat some names (attributes or methods) less public and the rules are as follows:

  • Most names in Python are public
  • The names that start with underscore _ are less public. In the sense, those names are for class internal use only
  • The names that start and end with double underscore __ are internal to Python. They are defined by the language. This way Python internals attributes are kept away from colliding with the application features above the internals. E.g __init__()
 
\n \n \n <span style="color: #808080; font-style: italic;">\n \n \n #Example 9\n \n \n
\n \n \n <span style="color: #ff7700; font-weight: bold;">\n \n \n class Parent_Class:\n \n \n
\n \n \n <span style="color: #ff7700; font-weight: bold;">\n \n \n def \n \n \n <span style="color: #0000cd;">\n \n \n __init__\n \n \n <span style="color: black;">\n ( \n <span style="color: #008000;">\n self \n <span style="color: black;">\n ): \n
\n <span style="color: #008000;">\n self. \n <span style="color: black;">\n x \n <span style="color: #66cc66;">\n = \n <span style="color: #483d8b;">\n "Animals" \n
\n <span style="color: #008000;">\n self.__y \n <span style="color: #66cc66;">\n = \n <span style="color: #483d8b;">\n "Pets" \n
\n
\n <span style="color: #808080; font-style: italic;">\n # Creating a derived class \n
\n <span style="color: #ff7700; font-weight: bold;">\n class Derived \n <span style="color: black;">\n (Parent_Class \n <span style="color: black;">\n ): \n
\n <span style="color: #ff7700; font-weight: bold;">\n def \n <span style="color: #0000cd;">\n __init__ \n <span style="color: black;">\n ( \n <span style="color: #008000;">\n self \n <span style="color: black;">\n ): \n
\n
\n <span style="color: #808080; font-style: italic;">\n # Calling constructor of \n
\n <span style="color: #808080; font-style: italic;">\n # Base class \n
Super. \n <span style="color: #0000cd;">\n __init__ \n <span style="color: black;">\n ( \n <span style="color: #008000;">\n self \n <span style="color: black;">\n ) \n
\n <span style="color: #ff7700; font-weight: bold;">\n print \n <span style="color: black;">\n ( \n <span style="color: #483d8b;">\n "Calling private member of base class: " \n <span style="color: black;">\n ) \n
\n <span style="color: #ff7700; font-weight: bold;">\n print \n <span style="color: black;">\n ( \n <span style="color: #008000;">\n self.__y \n <span style="color: black;">\n ) \n
\n
\n
\n <span style="color: #808080; font-style: italic;">\n # Driver code \n
obj1 \n <span style="color: #66cc66;">\n = Parent_Class \n <span style="color: black;">\n ( \n <span style="color: black;">\n ) \n
\n <span style="color: #ff7700; font-weight: bold;">\n print \n <span style="color: black;">\n (obj1. \n <span style="color: black;">\n x \n <span style="color: black;">\n ) \n </span style="color: black;"> \n </span style="color: black;"> \n </span style="color: black;"> \n </span style="color: #ff7700; font-weight: bold;"> \n </span style="color: black;"> \n </span style="color: black;"> \n </span style="color: #66cc66;"> \n </span style="color: #808080; font-style: italic;"> \n </span style="color: black;"> \n </span style="color: #008000;"> \n </span style="color: black;"> \n </span style="color: #ff7700; font-weight: bold;"> \n </span style="color: black;"> \n </span style="color: #483d8b;"> \n </span style="color: black;"> \n </span style="color: #ff7700; font-weight: bold;"> \n </span style="color: black;"> \n </span style="color: #008000;"> \n </span style="color: black;"> \n </span style="color: #0000cd;"> \n </span style="color: #808080; font-style: italic;"> \n </span style="color: #808080; font-style: italic;"> \n </span style="color: black;"> \n </span style="color: #008000;"> \n </span style="color: black;"> \n </span style="color: #0000cd;"> \n </span style="color: #ff7700; font-weight: bold;"> \n </span style="color: black;"> \n </span style="color: black;"> \n </span style="color: #ff7700; font-weight: bold;"> \n </span style="color: #808080; font-style: italic;"> \n </span style="color: #483d8b;"> \n </span style="color: #66cc66;"> \n </span style="color: #008000;"> \n </span style="color: #483d8b;"> \n </span style="color: #66cc66;"> \n </span style="color: black;"> \n </span style="color: #008000;"> \n </span style="color: black;"> \n </span style="color: #008000;"> \n </span style="color: black;">\n \n \n </span style="color: #0000cd;">\n \n \n </span style="color: #ff7700; font-weight: bold;">\n \n \n </span style="color: #ff7700; font-weight: bold;">\n \n \n </span style="color: #808080; font-style: italic;">
Copy code
About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio