Sei sulla pagina 1di 8

6/6/2019 5 Examples to Jumpstart Object Oriented Programming in Python

Reduce Bounces Up To
98% Accuracy 99%, Real-Time API, 24/7
Support, Bulk Email
Guaranteed Veri cation

≡ Menu

Home
Free eBook
Start Here
Contact
About

5 Examples to Jumpstart Object Oriented


Programming in Python
by Aanisha Mishra on March 14, 2019

Like 3 Tw eet

OOP stands for Object Oriented Programming. This concept is a style of solving programming problems where
properties and behavior of a real-life object is packaged as a single entity in the code.

This style of coding enables modularizing and scaling with least amount of issues.

Python is a dynamically typed, high level interpreted programming language. Python supports several OOP features
including the following:

Classes and Objects


Encapsulation
Inheritance
Polymorphism

1. Classes in Python

Class is a blueprint of the real-life entity. In Python, it is created using the class keyword as shown in the following code
snippet.

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

https://www.thegeekstuff.com/2019/03/python-oop-examples/ 1/8
6/6/2019 5 Examples to Jumpstart Object Oriented Programming in Python

In the above:

class – Here is a class named Person.


Constructors have the default name __init__. They are functions that are implicitly called when an object of the
class is created.
All instance methods including the constructor have their first parameter as self.
self refers to instance that is being referenced while calling the method.
name and age are the instance variables.

If you are new to Python, refer to this: Python Introduction Tutorial – Variable, String, Function Examples

2. Objects in Python

Once a Person class is defined you can use it to create an instance by passing values as shown below.

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

if __name__ == "__main__":
p = Person("ranjeeta", 23)
print(p.name)

In the above:

p – is the name of the object that we are creating based on Person class
Even though the class has three parameters (self, name, age), we’ll still pass only name and age while creating an
object, as we don’t need to refer self here. It’s implicit.
Once an object is created, you can refer to the attributes of the object using a dot. For example, p.name refers to
the name attribute of that particular object

3. Inheritance in Python

As the name suggest, this concept is about inheriting properties from an existing entity. This increases reusability of code.
Single, Multiple and Multi-level inheritances are few of the many types supported by Python.

The following example shows how to use inheritance in python:


https://www.thegeekstuff.com/2019/03/python-oop-examples/ 2/8
6/6/2019 5 Examples to Jumpstart Object Oriented Programming in Python
class Person:
def __init__(self):
pass

# Single level inheritance


class Employee(Person):
def __init__(self):
pass

# Multi-level inheritance
class Manager(Employee):
def __init__(self):
pass

# Multiple Inheritance
class Enterprenaur(Person, Employee):
def __init__(self):
pass

In multiple inheritance, classes are inherited from left to right inside parenthesis, depending on Method Resolution Order
(MRO) algorithm of Python.

4. Encapsulation in Python

It is the concept of wrapping data such that the outer world has access only to exposed properties. Some properties can
be hidden to reduce vulnerability. This is an implementation of data hiding. For example, you want buy a pair of trousers
from an online site. The data that you want is its cost and availability. The number of items present and their location is
information that you are not bothered about. Hence it is hidden.

In Python this is implemented by creating private, protected and public instance variables and methods.

Private properties have double underscore (__) in the start, while protected properties have single underscore (_). By
default, all other variable and methods are public.

Private properties are accessible from within the class only and are not available for child class(if inherited). Protected
properties are accessible from within the class but are available to child class as well. All these restrictions are removed
for public properties.

The following code snippets is an example of this concept:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def _protected_method(self):
print("protected method")
def __private_method(self):
print("privated method")

if __name__ == "__main__":
p = Person("mohan", 23)
p._protected_method() # shows a warning
p.__private_method() # throws Attribute error saying no such method exists

5. Polymorphism in Python

https://www.thegeekstuff.com/2019/03/python-oop-examples/ 3/8
6/6/2019 5 Examples to Jumpstart Object Oriented Programming in Python

This is a concept where a function can take multiple forms depending on the number of arguments or type of arguments
given to the function.

class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def show_salary(self):
print("Salary is unknown")

class Employee(Person):
def __init__(self, name, age, salary):
super().__init__(name, age)
self.salary = salary
def show_salary(self):
print("Salary is", self.salary)

if __name__ == "__main__":
p = Person("y", 23)
x = Employee("x", 20, 100000)
p.show_salary() # Salary is unknown
x.show_salary() # Salary is 100000

In the above example, super keyword is used to call a method of parent class. Both classes have the method
show_salary. Depending on the object type that makes a call to this function, the output varies.

Python has inbuilt-polymorphism functions as well. One of the simplest examples is the print function in python.

print("Hello there", end=" ")


print("I am Aanisha")
print(len([1, 2, 3, 4, 5]))

Output of the above code will be:

Hello there I am Aanisha


5

In the above code snippet:

The end keyword parameter changed the functionality of print function. Hence it did not end ‘Hello There’ with an
end-line.
len([1, 2, 3, 4, 5]) in third line return an int. The print recognizes the data type and implicitly converts it to string
and prints it to the console.

Tw eet Like 3 > Add your comment

If you enjoyed this article, you might also like..

1. 50 Linux Sysadmin Tutorials Awk Introduction – 7 Awk Print Examples


2. 50 Most Frequently Used Linux Commands (With Advanced Sed Substitution Examples
Examples) 8 Essential Vim Editor Navigation Fundamentals
3. Top 25 Best Linux Performance Monitoring and 25 Most Frequently Used Linux IPTables Rules
Debugging Tools Examples
4. Mommy, I found it! – 15 Practical Linux Find Turbocharge PuTTY with 12 Powerful Add-Ons
Command Examples
https://www.thegeekstuff.com/2019/03/python-oop-examples/ 4/8
6/6/2019 5 Examples to Jumpstart Object Oriented Programming in Python

5. Linux 101 Hacks 2nd Edition eBook

{ 1 comment… add one }

Temizzi March 15, 2019, 3:15 am

Great article.. I hope you will write more articles on Python as this is most popular languages not for Dev only but
also for tester, sysadmin, data scientists and others..

Link

Leave a Comment

Name

Email

Website

Comment

Submit

Notify me of followup comments via e-mail

Next post: 12 AWS opsworks-cm server CLI Examples to Manage Chef or Puppet OpsWorks Server

Previous post: 5 Steps for Code Changes Only on Git Branch and Merge to Master Once Done

RSS | Email | Twitter | Facebook | Google+

Custom Search Search

https://www.thegeekstuff.com/2019/03/python-oop-examples/ 5/8
6/6/2019 5 Examples to Jumpstart Object Oriented Programming in Python

EBOOKS

Linux 101 Hacks 2nd Edition eBook - Practical Examples to Build a Strong Foundation in Linux
Bash 101 Hacks eBook - Take Control of Your Bash Command Line and Shell Scripting
Sed and Awk 101 Hacks eBook - Enhance Your UNIX / Linux Life with Sed and Awk
Vim 101 Hacks eBook - Practical Examples for Becoming Fast and Productive in Vim Editor
Nagios Core 3 eBook - Monitor Everything, Be Proactive, and Sleep Well

The Geek Stuff


17,371 likes

Like Page Share

2 friends like this

POPULAR POSTS

15 Essential Accessories for Your Nikon or Canon DSLR Camera


12 Amazing and Essential Linux Books To Enrich Your Brain and Library
50 UNIX / Linux Sysadmin Tutorials
50 Most Frequently Used UNIX / Linux Commands (With Examples)
How To Be Productive and Get Things Done Using GTD
30 Things To Do When you are Bored and have a Computer
Linux Directory Structure (File System Structure) Explained with Examples
Linux Crontab: 15 Awesome Cron Job Examples
Get a Grip on the Grep! – 15 Practical Grep Command Examples
Unix LS Command: 15 Practical Examples
15 Examples To Master Linux Command Line History
Top 10 Open Source Bug Tracking System
https://www.thegeekstuff.com/2019/03/python-oop-examples/ 6/8
6/6/2019 5 Examples to Jumpstart Object Oriented Programming in Python

Vi and Vim Macro Tutorial: How To Record and Play


Mommy, I found it! -- 15 Practical Linux Find Command Examples
15 Awesome Gmail Tips and Tricks
15 Awesome Google Search Tips and Tricks
RAID 0, RAID 1, RAID 5, RAID 10 Explained with Diagrams
Can You Top This? 15 Practical Linux Top Command Examples
Top 5 Best System Monitoring Tools
Top 5 Best Linux OS Distributions
How To Monitor Remote Linux Host using Nagios 3.0
Awk Introduction Tutorial – 7 Awk Print Examples
How to Backup Linux? 15 rsync Command Examples
The Ultimate Wget Download Guide With 15 Awesome Examples
Top 5 Best Linux Text Editors
Packet Analyzer: 15 TCPDUMP Command Examples
The Ultimate Bash Array Tutorial with 15 Examples
3 Steps to Perform SSH Login Without Password Using ssh-keygen & ssh-copy-id
Unix Sed Tutorial: Advanced Sed Substitution Examples
UNIX / Linux: 10 Netstat Command Examples
The Ultimate Guide for Creating Strong Passwords
6 Steps to Secure Your Home Wireless Network
Turbocharge PuTTY with 12 Powerful Add-Ons

CATEGORIES

Linux Tutorials
Vim Editor
Sed Scripting
Awk Scripting
Bash Shell Scripting
Nagios Monitoring
OpenSSH
IPTables Firewall
Apache Web Server
MySQL Database
Perl Programming
Google Tutorials
Ubuntu Tutorials
PostgreSQL DB
Hello World Examples
C Programming
C++ Programming
DELL Server Tutorials
Oracle Database
VMware Tutorials

About The Geek Stuff

https://www.thegeekstuff.com/2019/03/python-oop-examples/ 7/8
6/6/2019 5 Examples to Jumpstart Object Oriented Programming in Python

My name is Ramesh Natarajan. I will be posting instruction guides, how-to, troubleshooting tips and
tricks on Linux, database, hardware, security and web. My focus is to write articles that will either teach you or help you
resolve a problem. Read more about Ramesh Natarajan and the blog.

Contact Us

Email Me : Use this Contact Form to get in touch me with your comments, questions or suggestions about this site. You
can also simply drop me a line to say hello!.

Follow us on Google+

Follow us on Twitter

Become a fan on Facebook

Support Us

Support this blog by purchasing one of my ebooks.

Bash 101 Hacks eBook

Sed and Awk 101 Hacks eBook

Vim 101 Hacks eBook

Nagios Core 3 eBook

Copyright © 2008–2018 Ramesh Natarajan. All rights reserved | Terms of Service

https://www.thegeekstuff.com/2019/03/python-oop-examples/ 8/8

Potrebbero piacerti anche