Object Oriented Programming in Python

Object Oriented Programming in Python

How OOP concepts work in Python

ยท

2 min read

In this article, we are going to discuss the four pillars of OOP -

  • Encapsulation
  • Abstraction
  • Inheritance
  • Polymorphism

in Python. ๐Ÿ•ต๐Ÿผ

1. Encapsulation ๐Ÿ’Š

Create a class

widget.py

class Widget:
    def __init__(self):

The __init__ (constructor) method is called when an object is created of this class type.

Add properties and member functions to this class

class Widget:
    def __init__(self, type:str, id:int, color=None):
        self.type = type
        self.id = id
        self.color = color
    def show(self):
        print("Displaying widget ", self.id, "in color ", self.color)

Create instance(object) of this class

You can set it's properties and call it's member functions.

window = Widget('Window', 1, 'black')
window.show()
window.color = 'white'
window.show()

You will see the following output - image.png

2. Abstraction ๐Ÿ‘โ€๐Ÿ—จ

Hide data

You can create private properties and member functions for your class by prefixing them with a underscore_ or a double underscore __

class Widget:
    color = None
    id = None
    # Private property of the widget
    __position = 0
   def __init__(self, type:str, id:int, color=None):
        self.type = type
        self.id = id
        self.color = color
    def show(self):
        print("Displaying widget ", self.id, "in color ", self.color)
    def show_position(self):
        print("Widget position ", self.__position)

Update private data of the Widget class

window.__position = 1
window.show_position()

Output -

Widget position  0

You cannot update __position attribute because it's private.

3. Inheritance ๐Ÿง’

Inherit the Widget class

class Popup(Widget):
    def __init__(self, type:str, id:int, size:int, color=None):
        super().__init__(type, id, color)
        self.size = size

In the above code super().__init__ calls the contructor(__init__) of the parent class. And size is the additional property we created in the child class.

Create a Popup Widget

popup = Popup(type='Popup', id=2, size=5)
popup.show()

The output of the above code is - image.png

3. Polymorphism ๐Ÿ‘ฉโ€๐Ÿš’ ๐Ÿ‘ฎโ€โ™‚๏ธ๐Ÿ•ต๏ธ

Update an inherited function

class Popup(Widget):
    def __init__(self, type:str, id:int, size:int, color=None):
        super().__init__(type, id, color)
        self.size = size
    def show(self):
        print("Displaying popup widget", self.id, "of size", self.size)

Call this inherited function

popup = Popup(type='Popup', id=2, size=5)
popup.show()

Output - image.png

We successfully modified the behavior show of the child Popup class to be different from the parent Widget class.

Have fun solving problems using OOP in Python!

ย