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):
        self.company = 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
1.company of fan
2.color of fan
3.number of wings of fan

How to create an object for a class ?

usha_fan = Fan(
   company="usha",
   color="blue",
   number_of_wings=3
)

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>

>>> usha_fan.company
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):
		self.name = 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):
		print("Woof!")


class Cat(Animal):
   
   def talk(self):
      print("Meow!")

# 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")
>>> c.talk()
Out: Meow!


>>> dog = Dog("Rocky")
>>> dog.talk()
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.

for more details please refer to python docs

Posted On 19 June 2014 By MicroPyramid


Need any Help in your Project?Let's Talk

Latest Comments
Unit testing with selenium-python

Unit testing with selenium-python. Unit test case example to test the front-end

Continue Reading...
Tips to choose the best custom software development company

Choosing the best company for your software development needs is the most important step. This blog explains you tips to outsource custom software development services.

Continue Reading...
WSGI explanation with simple APP

The main goal of WSGI is to facilitate easy interconnection of servers and web frameworks/applications. WSGI defines a standerd API for web servers(uWSGI, Twisted, Gunicorn) …

Continue Reading...
Understanding self and __init__ method in python Class.

Understand self and __init__ method in python Class?
Before understanding the "self" and "__init__" methods in python class, it's very helpful if we have the idea …

Continue Reading...
List of python class special methods or magic methods

python class special methods or magic methods. magic methods allow us to override or add the default functionality of python objects. One of the biggest …

Continue Reading...
Building and Parsing XML Document using Python

Creating XML document with required elements, Then Parsing it using Python to generate a serialized form of its contents.

Continue Reading...
Working with python collections Counter

Python collections - Counter is to count the frequency of character, OrderedDict is to track the order of the contents in which they are added …

Continue Reading...
Python to Debian package: Simple, Easy and Fast

Packaging python script to debian follows strict instructions, using the following instructions, most of the steps can be skipped hence making it easy and fast.
If …

Continue Reading...
Sending SMS, MMS using Twilio.

A simple Tutorial on sending SMS and MMS in python using Twilio. In this tutorial you will learn how to send SMS, MMS and checking …

Continue Reading...
Customize and Embed Vimeo Videos using Python Requests.

Using python requests and vimeo endpoints it becomes very easy and simple to upload our videos and customize them.

Vimeo Access token:
1. Create an …

Continue Reading...
Getting Started with the IPython Notebook

IPython is a set of tools developed to make it easier for the programmers to work with Python and data. IPython provides extensions to the …

Continue Reading...
Python Arrow To Show Human Friendly Time

Arrow is a python library and command-line tool to genrerate, manipulate dates, times, timestamps.
use of arrow:
With the use of arrow, we can also create, manipulate, …

Continue Reading...
Working with python collections part 1

Python Collections - named tuple is to access by the names specified and deque is to append and pop the elements from both sides of …

Continue Reading...
Building Documentation with readthedocs

In this blog, I'm going to explain you how to write the Sphinx docs using reStructuredText to host in the Read the Docs.

Installing Sphinx

Continue Reading...
Create excel file, Insert image, Draw Bar Graphs in excel files in python using xlsxwriter

Xlsxwriter is a python module through which we can write data to Excel 2007+ XLSX file format. In this blog post we learn to write …

Continue Reading...
Integrate Twitter Social API into Django App

Integrating Twitter sign in (OAuth) in Django App, which includes
1. Capturing username via Twitter Login
2. Updating authenticated user current status on twitter(tweets).

Continue Reading...
How to implement Case Insensitive CSV DictReader in python

In general use cases we upload the CSV files to the system to store huge amount of data by uploading single file. For example in …

Continue Reading...
Python using yield and generators.

Generators are memory efficient. They allow us to code with minimum intermediate arguments, less data structures. Generators are of two types, generator expressions and generator …

Continue Reading...
Introduction to Object Oriented Programming with Python 3

Introduction to Object Oriented Programming with Python

Continue Reading...
Python Coding Techniques and Programming Practices

Coding techniques and programming practices are one of the features of a professional programmer. While writing code to solve a problem programmer should make simple …

Continue Reading...
FABRIC – LEARNING PART 2

Using Fabric, we can develop interactive script for ec2 region, ec2 flavour amazon web services. For this, you need aws account, security group, key pair, …

Continue Reading...
Generating PDF Files in Python using xhtml2pdf

There are many ways for generating PDF in python. In this post I will be presenting PDF files generation with xhtml2pdf.

xhtml2pdf: xhtml2pdf is a …

Continue Reading...
Using Python xlwt generating CSV writer and Excel files

In most of the cases, you need to export the data from your database to different formats. In this post I will show you how …

Continue Reading...
How to access development server publicly using Localtunnel

We do need to expose our local server to hit call-back URLs while programming with other APIs. There is a tool called local tunnel from …

Continue Reading...
How to generate PDF Files from HTML In Python using PDFKIT

There are many approches for generating PDF in python. pdfkit is one of the better approache as, it renders HTML into PDF with various image …

Continue Reading...
Converting Audio and Video files using FFMPEG Tool

FFMPEG is a command-line tool that converts audio or video to required formats, which handle multimedia data. It can also capture and encode in real-time.

Continue Reading...
Python Web Scraping with Beautiful soup

Download all One Piece animation series episodes by scraping site using BeautifulSoup python library.

Continue Reading...
Publishing Python Modules with PIP via PyPi

We'll install so many packages in our day to day python development. Now in this blog post, we'll try to know how to create our …

Continue Reading...
Programming with python: Decorators

Python decorators supports aspect-oriented programming. It is used to add or modify code in functions or classes. Using decorators will provide security, tracing, looking ..etc …

Continue Reading...
Vim for Python Web Development

Having a good environment setup is important for effective, fast and easy coding. We have different IDE's like eclipse, pycharm, sublime etc.. which are powerful …

Continue Reading...
Understanding Python Properties

Python Properties is a class for managing class attributes in Python. Property( ) is a built-in function that creates and returns a property object

Syntax:
attribute_name …

Continue Reading...
QRCode generation in python

A Quick Response code(QRCode) is a two-dimensional pictographic code used for its fast readability and comparatively large storage capacity. The code consists of black modules …

Continue Reading...
Understanding Audio Quality: Bit Rate, Sample Rate

Audio Quality is the accuracy and enjoyability of the audio which the user can listen from an electronic device. Audio quality depends upon the bit …

Continue Reading...
Programming with python Descriptors (_get_, _set_, _delete_) - MicroPyramid

Python descriptors are object attributes that are only invoked for new style of classes. Python descriptors comes under the category of meta programming(code that manipulates …

Continue Reading...
Debugging in Python

When something goes wrong with your code instead of using standard debugging techniques such as print statements use debugging tools. I found two great tools …

Continue Reading...
Python development environment on windows

Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of …

Continue Reading...

Subscribe To our news letter

Subscribe and Stay Updated about our Webinars, news and articles on Django, Python, Machine Learning, Amazon Web Services, DevOps, Salesforce, ReactJS, AngularJS, React Native.
* We don't provide your email contact details to any third parties