python

Learn Object-Oriented Programming in Python

By Rasyue | On July 12, 2020

In this tutorial, we will learn about the concept of Object-Oriented Programming in Python (OOP Python). If you have been having trouble understanding the concept of OOP, this article will help you to quickly understand and master it. So, jump right in!

OOP Python – Introduction

Python in 2020 is still consider as one of the top languages and a lot of people are still using this language. Mainly because Python can be considered as a casual and easy to type language.

You can write a Python script to achieve a lot of purpose like starting up a server, creating an API endpoint, build a website with Python’s various web frameworks, data science, machine learning and a lot more.

In this python tutorial, we are going to talk about Object-Oriented Programming in Python. We are going to see to what extend can we use OOP in Python. If you are new to Object-Oriented Programming, you are welcome to check my post on Object-Oriented Programming in PHP to help you to understand the basic of OOP.

OOP Python – Class, Object & Constructor in Python OOP

So, let’s get to work. First, let’s try to create a Class in Python and create an instance of it which we called as an Object.

import datetime

class Rasyue:

    def __init__(self, post_name, post_author, post_date, blog_name):
        self.post_name = post_name
        self.post_author = post_author
        self.post_date = post_date
        self.blog_name = blog_name
       

    def postdetails(self):
        date_time =  self.post_date.strftime("%Y/%m/%d")

        print("The title of this post is "+self.post_name+". It was written by "+self.post_author+" on "+date_time+" on "+self.blog_name)

rasyue = Rasyue(
    "Object-Oriented Programming in Python",
    "Rasyue",
    datetime.date(2020, 7, 1), # year, month, day
    "Rasyue.com"
)

rasyue.postdetails()

Okay, pretty basic stuff that we wrote above. To help you understand the above better, we first create a class name Rasyue and then in the Class, we define the constructor which is the __init__.

But, what about the self, you may ask ?

OOP Python – self

Well, the self refers to the Class itself. The keyword can be anything, it does not really have to be self. You can replace it with any keyword you like and use it the same way. When I say that it refers to the Class itself, it means if you try to use the properties and methods of the Class itself, you have to use the self. See the example below.

import datetime

class Rasyue:

    def __init__(self, post_name, post_author, post_date, blog_name):
        self.post_name = post_name
        self.post_author = post_author
        self.post_date = post_date
        self.blog_name = blog_name
       
    def printDetails(self):
        print("My blog is "+self.blog_name)

    def postdetails(self):
        date_time =  self.post_date.strftime("%Y/%m/%d")

        print("The title of this post is "+self.post_name+". It was written by "+self.post_author+" on "+date_time+" on "+self.blog_name)
        self.printDetails()

rasyue = Rasyue(
    "Object-Oriented Programming in Python",
    "Rasyue",
    datetime.date(2020, 7, 1), # year, month, day
    "Rasyue.com"
)


rasyue.postdetails()

OOP Python – Inheritance

Now, let’s see how Inheritance works in Python. Inheritance is another aspect in OOP that allows a Class to inherits another Class. A Parent Child relationship. This allows the Child Class to use any methods or properties from the Parent Class.

import datetime

#creates the Parent Class first
class RasyueParent:

    def __init__(self):
        self.post_name = "Object Oriented Programming in Python"
        self.blog_name = "Rasyue.com"
       

    def postdetails(self):
        print("The title of this post is "+self.post_name+". Written on "+self.blog_name)


#creates the Child Class that inherits the Parent Class RasyueParent
class RasyueChild(RasyueParent):

    def childpostdetails(self):
       print("This is from the Child Class")


r = RasyueChild()
r.childpostdetails()
r.postdetails()

Method Overriding in Python

Method Overriding is when a Child class has a method that overrides the method from the Parent Class. Usually the method name will be the same. Refer to the code below.

import datetime

#creates the Parent Class first
class RasyueParent:

    def __init__(self):
        self.post_name = "Object Oriented Programming in Python"
        self.blog_name = "Rasyue.com"
       

    def postdetails(self):
        print("The title of this post is "+self.post_name+". Written on "+self.blog_name)
    



#creates the Child Class that inherits the Parent Class RasyueParent
class RasyueChild(RasyueParent):

    def postdetails(self):
       print("This is from the Child Class")


r = RasyueChild()
r.postdetails()

When you run the above script, it will print out the message from the Child Class. This is because the method with the same name in the Child Class overrides the same method from the Parent Class.

Data Encapsulation in Python

Data encapsulation is an aspect of OOP in Python where you can set properties in a Class as private.

import datetime

class Rasyue:

    def __init__(self, post_name, post_author, post_date, blog_name):
        self.__post_name = post_name
        self.__post_author = post_author
        self.__post_date = post_date
        self.__blog_name = blog_name
       
    def setpostname(self, new_post_name):
        self.__post_name = new_post_name

    def postdetails(self):
        date_time =  self.__post_date.strftime("%Y/%m/%d")

        print("The title of this post is "+self.__post_name+". It was written by "+self.__post_author+" on "+date_time+" on "+self.__blog_name)
        

rasyue = Rasyue(
    "Object-Oriented Programming in Python",
    "Rasyue",
    datetime.date(2020, 7, 1), 
    "Rasyue.com"
)


rasyue.postdetails()
rasyue.setpostname("Object Oriented Programming in PHP")
rasyue.postdetails()

Noticed the double underline for each of the properties, __ . When you set properties as private, the only way you can change the value of the properties is through writing methods that will change the value which we often call as setter.

Polymorphism in Python

Polymorphism is an aspect in OOP to use a common interface for multiple forms (data types). Let’s see how Polymorphism works in Python programming language through Class methods.

class Elephant:
    def __init__(self, name, weight):
        self.name = name
        self.weight = weight

    def info(self):
        print(f"My name is {self.name}. I am {self.weight} kilogram and I am an elephant")

    def animal_sound(self):
        print("Rumbless~")


class Tiger:
    def __init__(self, name, weight):
        self.name = name
        self.weight = weight

    def info(self):
        print(f"My name is {self.name}. I am {self.weight} kilogram and I am a tiger.")

    def animal_sound(self):
        print("Roaaarr")


elephant_test = Elephant("Dumbo", 125)
tiger_test = Tiger("Jiba", 95)

for animal in (elephant_test, tiger_test):
    animal.animal_sound()
    animal.info()
    animal.animal_sound()

To explain the above, first we created two Classes, Elephant & Tiger. Both Classes have the same methods and properties. When we try to iterate them in the for loop, it does no return an error even though both Objects are not from the same class. However due to Polymorphism, same method names, we can disregard the object and generalize calling the same methods.

I hope the above will be able to help you to understand Python better or help you in some way. I will be writing more Python Tutorial so stay tuned!

You are welcome to check my other tutorial on python here

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*
*