OOP — An Intro to Object Oriented Programming in Python

Chiraag K V
Artificialis
Published in
8 min readSep 1, 2021

--

Photo by Chris Ried on Unsplash

What is OOP?

Object Oriented Programming (OOP for short), is a programming paradigm (an approach to a certain programming problem) which is based on the concept of “Objects”.

Objects are variables that belong to a specific datatype. Whenever we print the type() of a variable, we are printing out which class or datatype it belongs to.

Classes

In OOP, classes are “blueprints” of a datatype, containing all of the attributes and methods it has. when we print out type(a), where “a” is an string, we get something like this:

We can see that the class “a” belongs to is string

Object “a” is an instance of class str. Instance, as the name suggests, is an occurrence of a class.

Summary

This section had its fair share of new words. To summarize:

  • Class: A blueprint of your custom datatype
  • Instance: An occurrence on the class, or the calling of a class
  • Object: the variable or the place in memory where the instance is stored

Code

A simple class and object

Four Pillars of OOP

1. Encapsulation

Methods and Attributes

Let’s take an example to understand this concept.

You want to buy a new TV. When you go to the electronics store, you see that each TV has attributes like length, width, resolution and speaker quality. We can write this as a class in Python like this:

An example of attributes

Woah! what is that def __init__ thing? Here, init stands for initialization. This a a special method known as constructor. Constructors “construct” a class by defining the attributes of a class.

may have also noticed the “self” in the parenthesis. Self refers to the instance of the class itself, indicating that the method belongs to the instance. With this, we can say that attributes are instance specific.

We have been talking about methods a lot, but what are they? Let’s go back to the TV example to understand this concept.

When you want to buy a TV, we also look at the features of the TV, like working of the remote or voice search. These can be seen as the methods of class TV. We can write this as:

An example of a method

This should be pretty simple to understand if you are familiar with functions. The output of this will be 13.

Summary

In encapsulation, the data (attributes) and the functionality (methods) are encapsulated in a class. I hope you see why this concept of OOP is important. Here, our code has only one (pretty small) file. In real life, when we are working with dozens files, this helps manage our code well. We can just import one class from one file to get all of the attributes and methods of that class.

2. Abstraction

Abstraction, as the name suggests, hides all unnecessary elements of our code and gives only what the user cares about.

Continuing with our TV example, whenever we press a button on the TV remote, we don’t actually care about how the TV receives the signal and how it changes the channel accordingly. All we care about is the channel changing. The TV abstracts away the unnecessary details and gives us the end product. We can write this as:

An example of Abstraction in OOP

This code outputs 5 after changing then channel.

Summary

Abstraction helps programmers to write code easily as they can just call the method and use it as they want instead of figuring out how every single thing works. This helps when we are building complex projects in real life. A practical use case can be importing a python library like NumPy, instantiating an array and calling methods on it.

3. Inheritance

To understand this concept, let’s extend our TV example to accommodate a TV and a washing machine. Both a TV and a washing machine need electricity and have a button to get switched one, something that all electrical appliances have. Can we say that both TV and washing machine inherit these things from a general blueprint of all electrical appliances?

Following the Italicised words, you can see that two classes — TV and Washing Machine, inherit functionality such as electricity input and switch from a class (called as a blueprint in the example) electrical appliance.

An example of Inheritance in OOP

In the WashingMachine class, I have commented out the __init__ constructor as inheriting from Appliance provides us with all of the attributes. If we do not pass the 'electricity' while instantiating the class, then we will get an error as .switch_on() method needs the input_type.

What you wouldn’t have seen before is the (Appliance) after the class declaration. This is done for inheriting from a parent class, where the parent class is inside the parenthesis.

Super()

In the above example, I have run the init function of the Appliance class to get the attributes needed. Instead of this, we can also use the super() function. This, way we need not add self inside the __init__() method.

Types of Inheritance

Types of Inheritance

Although these types look like a lot, they are basically the same thing done multiple times in different ways.

Summary

Inheritance is a very important concept of OOP where one class is able to use the attributes and methods of another class

4. Polymorphism

In our previous example, we created a switch_on() method. Let’s improve this method by telling the power needed for it to work by adding a “power” attribute and printing it out too.

An example of Polymorphism in OOP

This small change of adding .switch_on() method to both TV and WashingMachine class. The outputs of the .switch_on() method on all three objects are different. What I have shown is an example of polymorphism.

Polymorphism is made up of two words — Poly, which means many and morph, which means forms. Here, the switch_on() method is common to all classes, but is used differently in each class.

Summary

Polymorphism is a simple yet important concept that lets us use a specific method or attribute in multiple classes in multiple ways.

That’s it! With this, we are done with the 4 pillars of OOP.

Let’s now look into other useful concepts of OOP

Class Attributes, Class Methods and Static Methods

Class Attributes

These attributes belong to the class itself and not an instance of the class. To understand this, let’s build a game. This game has a User class with some attributes and methods. It also has a class attribute number_of_players to count the number of people playing the game.

The User Class with class attributes

Here, whenever we check the number_of_players, it is always one, no matter how many instances are created. To change that, we need to modify the class attribute.

Just as attributes are modified by methods, class methods modify class attributes. Let’s look into these class methods now.

Class Methods

Just like Class Attributes, Class Methods are methods belonging to the class itself and are called on the class itself. Let us use these methods to modify the number_of_players to update whenever a new object has be instantiated.

The User Class with class methods

I have added User.add_people() to the init function. This will add 1 to the number_of_players variable every time the __init__() function is called, i.e., every time the class gets instantiated. The other new syntax here is the @classmethod decorator. This decorator marks the functions defined below it as a class method. You can also see that the self has been replaced by cls. This is because the class method doesn’t belong to the instance, but the class. “cls” here refers to the class. This is also the reason for using cls.number_of_people — the attribute belongs to the class.

Static Methods

To understand Static methods, let’s take a real programming example. Let’s say that we are creating some functions related to maths like add, subtract, multiply and divide. We could create four independent functions, but that would be messy. In this kind of a situation, we can use static methods.

Static methods are basically multiple functions packaged into one class, so that we could use it as a method. In order to use them, we don’t need to instantiate the class.

The Math Class with static methods

Dunder Methods or Magic Methods

Dunder methods are a short form for “double underscore methods”. they are named using a notation like this : __methodname__. Certain python functions like len(), str(), int() are dunder methods under the hood. To see how they work, let’s create a class and modify the len function.

Dunder methods

Here, I have created a class that inherits from Python’s in-built list class (Inheritance). I have created a class method convert() that uses the cls() function to convert any given list into an instance of the ExtendedList class.

Then I changed the list class’s in-built dunder method len() to return only 1000 (polymorphism). As len dunder methods can be used as functions, I printed out the len() of a list and the len() of an ExtendedList. The len function, when used on an ExtendedList, returned only 1000 and when called on a list, return the length of the list.

Note: Only certain dunder methods can be called using special syntax like functions.

Summary

That’s it! These are the most useful concepts of OOP that I’ve come across. Have I missed anything? If so, please let me know.

That’s all for this one,

Bye!

Every week, Artificialis sends out the best from its community.

--

--