Innovate anywhere, anytime Your cloud-based dev studio.

Introduction to Object Oriented Programming with Python 3


Python supports both Procedural and Object Oriented approches in problem solving.
We can solve the complex problems with procedural approach but it makes difficulty in organizing  and readability of the code. By using object oriented approach we can better organize the code and readability.

What is a class ?

Class is a set or category of things having some property or attribute in common and differentiated from others by kind, type, or quality. In technical terms we can say that class is a blue print for individual objects with exact behaviour.

What is object ?

object is one of instances of the class. which can perform the functionalities which are defined in the class.

In object oriented programming we have 4 basic concepts.

  1. Abstraction: It is the process of modeling or breaking complex realworld problem into classes without implementing the functionality. They can be Inherited or implemented in future.
  2. Polymorphism: It is defined as using the function or an operator in a different way to different types of data.
  3. Encapsulation: It is defined as hiding the implementation details of a class from other objects.
  4. Inheritance: It is the process of acquiring the functionalities and properties from the parent classes.

We can also have other terminology in OOP's

method overloading: By using method overloading we can use the parent Class method functionality and we can add extra functioanlity.

method overriding: By using method overriding we can replace the functionality of the parent Class method with our own functionality.

Let's take an example of a electric fan.

Data: Electric fan have four wings. It has color blue and it's a usha company fan. we can regulate(speed up or speed down) the speed of the fan. we can also swith-off and switch-on the fan.

Let's construct the class for Fan with above data

class Fan(object):
    # initialize the fan with basic data
    def __init__(self, company, color, number_of_wings): = company
        self.color = color
        self.number_of_wings = number_of_wings

    def switch_on(self):
        print("fan started")

    def switch_off(self):
        print("fan stopped")

    def speed_up(self):
        print("speed increased by 1 unit")

    def speed_down(self):
        print("speed decreased by 1 unit")

How to get attributes and methods from data or our requirement/problem ?

First we have to analyze the problem. After analyzing the problem findout the  verbs or required functionalities from our requirement/problem. These verbs or required functionalties will become methods to our class.
In above example we have below requirements 
1. switch on the fan
2. switch off the fan
3. speed up the fan
4. speed down the fan
You can find that we have defined the same functionalities as methods to our class Fan.

Now, Find out the adjectives, nouns from the data these will become our attributes.
In above example we have the following attributes of fan
2.color of fan
3.number of wings of fan

How to create an object for a class ?

usha_fan = Fan(

We have created an object for class "Fan". Now, we can use the functionality of "Fan object". We can call the fan object as fan instance also.

# accessing attributes from an object
>>> usha_fan
Out: <__main__.Fan at 0x7f105819ff50>

Out: 'usha'

>>> usha_fan.color
Out: 'blue'

>>> usha_fan.number_of_wings
Out: 3

# accessing methods from an object
>>> usha_fan.switch_on()
Out: fan started

>>> usha_fan.switch_off()
Out: fan stopped

>>> usha_fan.speed_up()
Out: speed increased by 1 unit

>>> usha_fan.speed_down()
Out: speed decreased by 1 unit

Lets consider the following scenario to understand the basic concepts of OOPS.
Human, Dogs, Cats, etc. belongs to the animal kingdom according to the biology. All of the animals have some common properties aswell as unique properties from one another. 

Example for Inheritance and Polymorphism

class Animal(object):

	""" This is abstract class for Animal with common properties """

	def __init__(self, name='Animal', no_of_legs): = name
		self.no_of_legs = no_of_legs

	def kingdom(self):
		print("Animal Kingdom")

	# abstracted methods
	def talk(self):
		raise Exception("NotImplemented method")

	def eat(self):
		raise Exception("NotImplemented method")

class Dog(Animal):

	def talk(self):

class Cat(Animal):
   def talk(self):

# Inheritance Example [Cat got the method kingdom from its parent Animal]
>>> cat = Cat("Missy")
>>> cat.kingdom()
Out: Animal Kingdom

# Polymorphism Exmple [same method work differently for different data types(Cat, Dog)]
>>> cat = Cat("Missy")
Out: Meow!

>>> dog = Dog("Rocky")
Out: Woof!

Example for Encapsulation:

class Circle(object):

   pi = 3.141592

   def __init__(self, radius=1):
       self.radius = radius 

   def area(self):
       return self.radius * self.radius * Circle.pi

   def setRadius(self, radius):
       self.radius = radius

   def getRadius(self):
       return self.radius

# encapsulation example

>>> c = Circle()
>>> c.setRadius(15)
>>> c.area()
Out: 47.1

# from above example we dont need to know the formula for calculating area of circle

In many applications/frameworks  connecting to the database  we just create the database like
database = new Database()
database.connect(db_name="micropyramid", password="secret")
accually we don't know what's happening inside the method "connect" 
It hides the implementation details[not required to know ] this is called encapsulation.