Tuesday, July 22, 2014

Advance Object Oriented programming in Python


The following program will illustrates the method overriding concept onf OOP. Here parent and child classes have defined with the same method name and signature. According to context the method would be executed. The actual meaning of overriding means ignoring the parent method when both have same method signature, and executing the derived class method.

===== METHOD OVERRIDING SAMPLE PROGRAM =====

class FirstClass:            #define the super class  
 def setdata(self, value):     # define methods
  self.data = value # ‘self’ refers to an instance 
 def display(self):  
  print self.data

class SecondClass(FirstClass):  # inherits from FirstClass
 def display(self):  # redefines display
  print 'Current Data = %s'  % self.data
x=FirstClass()  # instance of FirstClass
y=SecondClass()  # instance of SecondClass
x.setdata('Before Method Overloading')
y.setdata('After Method Overloading')
x.display()
y.display()

===== Static and Class Method Sample Programs =====

class Students(object):
 total = 0
 def status():
  print '\n Total Number of studetns is :', Students.total
 status= staticmethod(status)
 def __init__(self, name):
  self.name= name
  Students.total+=1
print ‘Before Creating instance: ‘, Students.total
student1=Students('Guido')
student2=Students('Van')
student3=Students('Rossum')

Students.status() # Accessing the class attribute through direct class name 
student1.status() # Accessing the class attribute through an object
class Spam:
 numinstances = 0
 def count(cls):
  cls.numinstances +=1
 def __init__(self):
  self.count()
 count=classmethod(count)     # Converts the count function to class method
class Sub(Spam):
 numinstances = 0
class Other(Spam):
 numinstances = 0
S= Spam()
y1,y2=Sub(),Sub()
z1,z2,z3=Other(),Other(),Other()
print S.numinstances, y1.numinstances,z1.numinstances
print Spam.numinstances, Sub.numinstances,Other.numinstances

Regular Expressions in Python



This session about Python Regular expressions how we can work with patterns and the specific methods available in re module.

  1. match()
  2. group(), groups()
  3. search()
  4. compile()
  5. sub()

Regular expression sample in Python

Here is the sample for match function use.

#!/usr/bin/python
"""
This program illustrates the usage of match, group functions in re module
This also shows how to use re flags
"""
import re

line = "Python Orientation course helps professionals fish best opportunities"

m = re.match( r'(.*) helps (.*?) .*', line, re.I)

if m:
   print "m.group() : ", m.group()
   print "m.group(1) : ", m.group(1)
   print "m.group(2) : ", m.group(2)
else:
   print "Don't have match!!"
The output
>>> execfile('c:/pybin/rematch.py')
m.group() :  Python Orientation course helps professionals fish best opportunities
m.group(1) :  Python Orientation course
m.group(2) :  professionals

=======

Remove, Replace using re

Example for remove, replace the pattern in the given string
#!/usr/bin/python
import re

DOB = "07-11-1973# This is DOB "

# Delete Python-style comments
num = re.sub(r'#.*$', "", DOB)
print "DOB Num : ", num

# Remove anything other than digits
x = re.sub(r'\D', "", DOB)    
print "DOB without - : ", x


# Substituting other symbol in anything other than digits
FDOB = re.sub(r'\D', "/", num)    
print "DOB in new format : ", FDOB

=======

Searching Pattern

Example for Searching the pattern in a given string

""" This program illustrates is 
 one of the regular expression method i.e., search()"""
import re 
# importing Regular Expression built-in module
text = 'This is my First Regulr Expression Program'
patterns = [ 'first', 'that‘, 'program' ]
# In the text input which patterns you have to search

for pattern in patterns:
    print 'Looking for "%s" in "%s" ->' % (pattern, text),
    if re.search(pattern, text,re.I):
        print 'found a match!'
 # if given pattern found in the text then execute the 'if' condition
    else:
        print 'no match'
 # if pattern not found in the text then execute the 'else' condition
Python Regular Expression

Monday, July 14, 2014

Functions in Python


Heere we have experimenting with functions in Python, Functions can be defined for specific task, functions are prepared to reuse them. modular programming can be defined as breaking the bigger task into chunks of blocks this can be achived with the Python functions. Over all we are going to know in depth knowledge on how Python function is powerful then other structure programs.

We have seen some built-in functions which you don't need to import any modules.

  • str(), int(), float(), bool() -- type definitions
  • type(), id(), dir() --  introspecting the functions
  • len(), range() -- sequance collection related functions
  • print(), input(), raw_input() -- input output functions
Python Function overview
  1. Function definition 
  2. Calling Function in assignment
  3. Adding DocString to Function 
  4. Function Execution – Scope of variables
  5. The import and reload
  6. Defining inner functions
  7. Lambda functions

Function definition structure

1. Procedure - which do not have return statement
2. Function - which returns
3. Method - with in a class
4. Module - with in a py file

Defining Function in Python
Function Arguments
In Python we can create function without arguments. We can create with simple arguments with Python object types. We can also assign value for these arguments when calling function is not passed all required arguments then it will use thhese default arguments.

Functions returns
Like other programming languages Python also have 'return' keyword to send back the result of the task from the function. Function is a sub program it follows single entry and single exit. This return statement will be the last exiting statement, You may have multiple returns in a function only where that can be under certain conditional expressions. That means it will be in if-else blocks.

Function Calling
The function which has return statement such functions can be called in :

  1. assignment 
  2. expression
  3. output 

The following function example shows all the above variations.
#!/usr/bin/python

def add(x=10,y=1):
        return x+y
def printline():
        "This is procedure "
        print '#'*25
print "I'm in main now"

# Function call in an expression
x=add(100,3)+30
print "Expression       :", x

# Function call in assignment
y=add(50,50)
print "Assignment       :",y

# Function call in output
print "Output           :", add(200,300)
print "Default arguments:", add()
print "Partial arguments:", add(y=20)

# Procedure call
printline()



Lambda functions

The lambda function are inline functions, which don't have to define with 'def'. Here we define the function with 'lambda' keyword. These functions don't have any name, they are anonymus functions. These lamdda functions are useful when you have simple logic where it can be return output with a condition or a loop. Remember that, we cannot use it for complex logics with Lambda functions. Defining lambda syntax:
variable = lambda args : expression
Lambda fuction example:
#!/usr/bin/python

# Lambda function definition
m=lambda k: str(k/1024.0)+' MB'

# Calling function
print "m(204800):", m(204800)

g=lambda k: str(k/(1024*1024.0))+' GB'

print "G(40960000):", g(40960000)
The execution of lambda function as follows:
m(204800): 200.0 MB
G(40960000): 39.0625 GB
Lets try to build the script with more specific to system admin commands.
#!/usr/bin/python

import commands

prints=lambda:'#'*45

def checkDiskspace():
        """This function display diskspace usage"""
        print prints()
        d=commands.getoutput("df -h|grep dev")
        print d

def checkMem():
        "Checks free memory"
        print prints()
        m=commands.getoutput("free -m")
        print m

def checkCPULoad():
        "Checks load averages"
        print prints()
        c=commands.getoutput("uptime")
        print c

print "===main===="
checkDiskspace()
checkCPULoad()
checkMem()
print prints()


The output would be as follows:
pavanbsd@puppet:~/pybin$ ./utilfun.py
===main====
#############################################
df: `/var/lib/lightdm/.gvfs': Permission denied
/dev/sda1       6.8G  5.7G  825M  88% /
udev            1.8G  4.0K  1.8G   1% /dev
/dev/sdb5        21G   44M   20G   1% /tmp
/dev/sdc1       9.8G   23M  9.2G   1% /app
/dev/sr1        706M  706M     0 100% /media/Ubuntu 12.04.3 LTS i386
/dev/sr0         23M   23M     0 100% /media/VBOXADDITIONS_4.2.4_81684
#############################################
 12:11:56 up 1 day,  5:09,  1 user,  load average: 0.06, 0.08, 0.12
#############################################
             total       used       free     shared    buffers     cached
Mem:          3500       1622       1878          0         67       1407
-/+ buffers/cache:        147       3352
Swap:         1022          0       1022
#############################################
Here I have learned about positional arguments simple sentences I can say that:

 *args = list of arguments -as positional arguments
**kwargs = dictionary - whose keys become separate keyword arguments and the values become values of these arguments.

The syntax is the * and ** prefixing the argument, the names *args and **kwargs are only by convention but there's no hard requirement to use them.

Why *args, **args used?
*args and **kwargs are special-magic features of Python and they are not operators symbols in this context.
You would use *args when you're calling a function not sure how many arguments might be passed to the function, i.e. it allows you pass an arbitrary number of arguments to your function.

#!/usr/bin/env python
"""
Simple example of keyword arguments
With multiple ways to call the function
"""
def demo(**args):
    print args

demo()

demo(name='Pavan', gender='male', age=42)

d  = {'color' : 'BlueYellow', 'value':'+3v', 'make':'INDIA', 'version': 'v0.0.1'}

# here ** unpacking dictionaries
demo(**d)

The execution gives us:
~/pybin$ ./kwargs.py
{}
{'gender': 'male', 'age': 42, 'name': 'Pavan'}
{'color': 'BlueYellow', 'make': 'INDIA', 'version': 'v0.0.1', 'value': '+3v'}

You can call the ** args many ways here it is using for passing local list, Passing positional values with its name is more fun.

n_times = 10000
mycourse='Python Orientation'
mytraining = 'Vybhava Technologies!'
print "{mycourse} at {mytraining}  is experimenting is {n_times}x joy!".format(**locals())
>>> execfile('c:/pybin/kwargsex.py')

Python Orientation at Vybhava Technologies!  is experimenting is 10000x joy!

Differences between Python Procedure and Functions.
Differences between funciton module and Method
Differences between function and operator overloading
What is method overloading? What is method overriding?
How to import module in Python?

Importing modules

What is Python Module?

When a Python shell starts it only has access to a basic python functions (“int”, “dict”, “len”, “sum”, “range”, ...) “Modules” that contain additional functionality more methods, more reusability and more sharability. Use “import” keyword to tell the Python shell to load a module.

import os, sys
Namespaces are one honking great idea -- let's do more of those! (Zen of Python)
import this

Why importing modules in Python?

The major advantage comes when you split your program into several files for easier maintenance.

How to import modules in Python

A module can be imported by another program to make use of its functionality. This is how we can use the Python standard library as well You can import multiple modules.

import module1[, module2[,... moduleN]

Normally after module import we can use its containing functions by calling them with refering with the module name followed by period or dot(.) and the function/procedure name.

import modulename
a = modulename.function()

A module can be short-named that is alias for the module.
import modulename as mymod
a = mymod.function()

You can import only the function instead of whole functions in the modules which are not used.
from modulename import function
a = function()

You can also make the function alias.

from modulename import function as f
a = f()

Either you can import all the module content
from modulename import *

The following Python program is going to illustrate that importing the modules. A module can be set of functions defined in a .py file. Here we have experimented with mymath.py program with major math functions definations : multiply, add, sub, div. And these functions can be called in one more Python program where you can test the module function calls after importing them.

"""
File name : mymath.py
The python program is to illustrate the math functions.
"""

def multiply():
 print 'enter 2 numbers'
 a=input('>')
 b=input('>')
 c=a*b
 print 'product of', a, b, 'is', c

def add():
 print 'enter 2 numbers'
 a=input('>')
 b=input('>')
 c=a+b
 print c
 
def sub():
 print 10 - 3
 
def div(x,y):
 print x /y

The following program is invoking the functions that are defined in the mymath.py file.
""""
File Name: testmodule.py
This will give you the execution of all the functions imported from mymath.py

Example:
>>> execfile('c:/pybin/testmod.py')
7
multiply
enter 2 numbers
>3
>4
product of 3 4 is 12
Addition...
enter 2 numbers
>5
>6
11

"""

from mymath import *
 
mymath.sub()
print 'multiply'
multiply()
print 'Addition...'
add()


importing packages


Package is a directory of Python programs that have module code. A package is a collection of modules in directories that give a package hierarchy. __init__.py makes a directory to a package.
import dir1.dir2.module
from dir1.dir2.module import function
Use dot(.) instead f (/) - dir/dir2/module
from dir1.dir2.dir3.mod import function
 function()
import dir1.dir2.dir3.mod as mod
 mod.function()

The PYTHONPATH usage

PYTHONPATH is an environment variable set with the locations where the Python interpreter searches for user created modules. Typically, the module search path is defined as:
 export PYTHONPATH=.:/usr/local/lib/pythonX.X 
which is the current directory and library path, where you can add your Python module path say /home/sujith/pybin/modules appended to this PYTHONPATH. Let me tell you the trick to understand a module. You can get the module path from which they are imported using str() function on the module. How do we know it is a module? Use dir() function.

Generating Bytecode from .py

There could be bulk number of Python source files you might get in some cases where you need to use them in your source. To avoid slow interpretation we can create the intermediary code that is bytecode from each .py source file by compiling them. py_compile module we can generate the bytecode. This py_compile module have two important methods: compile() and compileall().Here compileall() function used to compile all Python files in an entire directory tree.
import py_compile
py_compile.compile('myscript.py')
or else you can do that at your command prompt as well as shown:
python -m py_compile myscript.py
python –m py_compile A.py B.py C.py  
python –m compileall –l pybin

Dynamic module loading

Here we have another dynamic trick that might be useful when you need to use some module which is in separate path(not in the PYTHONPATH or in current path) and you need in Python script/Shell; then you can use standard sys module. First you need to import sys (sys is a standard python module) and then append the new path to sys.path that is a string list.
import sys
sys.path.append('/home/sujith/pybin')

The __import__ method

myos = __import__(“os”) (O) To support some dynamic features.
myos=__import__("os")
>>> myos


>>> myos.getloadavg()
(0.14, 0.21, 0.51)
>>> myos.getgroups()
[4, 24, 27, 30, 46, 109, 124, 1000]
>>> myos.getcwd()
'/home/pavanbsd'


The __name__ of module


__name__ is an attribute for a module. A module ‘s __name__ will set to the string "__main__" when you start this module as a program. If you import the module, the module’s name will set to the module’s file name without .py suffix. The simple rule: your starting program have __name__ is set to “__main__”, otherwise it is just the module file name without .py suffix. To avoid ambiguity for Python interpretor we can write an if condition for main module.
if __name__=="__main__":
    call_fun()


Here we can do enhance our packages and sub-packages customized to build more powerful script utilities.

Sunday, July 13, 2014

Files IO & Pickles

How to make this FILE process in Python? 

The Standard Input, Standard Output are the two fileobjects genrally accessible from the operating system provided interfaces which allows us to change files.

How to redirect this output... normally output is coming from print command in the Python. Can you send the data/text to a file? Yes we can using file object.
File IO Process in Python

The file open modes

Python file open modes are same as C language by default it will be open in read mode. The open() method returns a file object or file pointing reference. 
Syntax: 
fileobject = open(file_name [, access_mode][, buffering]) 
where basic file operational mode can be 'r' (read), 'w'(write) or 'a'(append). 
The default mode is 'r' that is read mode and the file can be ANSI Text file or binary file (b). They can be opened in combined mode ‘rb+’ 
That every file that you opened in the code must be closed. The close() method closes an opened file object or you can dereferences.
Syntax: fileObject.close()

File Advanced open modes

File Advanced opening modes in Python

The file attributes

Following table have the list of the file object attributes. Which we can directly access them public.

AttributeDescription
file.closedReturns true if file is closed, false otherwise.
file.modeReturns access mode with which file was opened.
file.nameReturns name of the file.
# This program illustrates the file attributes

f=open('fileattr.py')
print "mode:",f.mode
print "name:",f.name

if f.closed:
        print f.name, " is closed"
else:
        print f.name," is not closed"

Its execution gives the output as follows
>>> execfile('fileattr.py')
mode: r
name: fileattr.py 
fileattr.py is not closed

We started experimenting with Files and Pickle soon we will update you on that... Object oriented pickling !!!

  1. Create your own object
  2.  Push the object into pickle
  3.  Dump, load functions explore
  4.  persistance of objects
  5.  Reusing the object after a restart of Python Shell

Pickle for Patient object persistance

import pickle
"""
This program is to illustrate the Pickle module usage in Python
"""

class Patient:
 def __init__(self, n, a):
  self.name=n; self.age=a
 
 def __repr__(self):
  return self
 
 def Printpatient(self):
  print self.name, self.age

if __name__=="__main__":
 """ This is main program for Patient database program """
 
 p=[] # This list is to dump
 x=[]  # This list is for load from pickle
 
 for i in range(0,2):
  n=raw_input('Enter name of the Patient:' )
  a=input('Enter age of the patiet: ')
  p.append(Patient(n,a))
 #Storing the list of Patient objects into a file
 fp=open('Patient.txt','wb') # Write in bin format
 pickle.dump(p,fp)
 fp.close()
  
 fp=open('Patient.txt','r+')
 x=pickle.load(fp)
 for i in x:
  i.Printpatient()

>>> execfile('c:/pybin/PatientFile.py')
Enter name of the Patient:Nageshwarrao
Enter age of the patiet: 89
Enter name of the Patient:Sridhar
Enter age of the patiet: 51
Nageshwarrao 89
Sridhar 51

Monday, July 7, 2014

Python Sequence Data Types: List, tuple



In this I would like to discuss about Python data types. Usually Python don't required any variable declarations with datatype but we should aware when we are dealing with the variable values and how it stores what type of data. Let's jump into our exploration on Python data types.

Python Mutable vs Immutable datatypes


In simple way to understand this using id() function that returns address of the variables. Mutable data type means the variable stores the data at one address even different operations (+,-,/,*,%) on the variable. The content of objects of immutable types cannot be changed after they are created.
Mutable objects

  1. bytearray
  2. list
  3. set
  4. dict

Immutable objects

  • int
  • float
  • long
  • complex
  • str
  • tuple
  • frozen set

Lets test a int data type and a list data type to evaluate the immutable values with int data type while doing arthematic operation on it. Similarly list example shows how mutable type uses the same address even when an element is modified or appended with new element.
>>> x=100
>>> type(x)

>>> id(x)
161334212
>>> x=x+1
>>> id(x)
161334200
>>> l=[10,20,30]
>>> type(l)

>>> id(l)
3073114060L
>>> l[2]=50
>>> l
[10, 20, 50]
>>> type(l)

>>> id(l)
3073114060L
>>> l.append(22)
>>> l
[10, 20, 50, 22]
>>> id(l)
3073114060L

Index and Sliceing of sequences

To access the individual elements of a tuple, list, or string using square bracket [] “array” notation. Note that all these sequences index starts with 0 based.
Positive index: count from the left and move towards right, all sequences index starting with 0
>>> t=(10.4,90,888,'SysAdmin')
>>> t[0]
10.4
>>> l=['one','python',4,'admin']
>>> l[0]
'one'
>>> s='Python for Administration'
>>> s[0]
'P'
Negative index: Now the count starts from right side of sequence, this will starts with –1. Using above sequences variables to illustrate
>>> t[-1]
'SysAdmin'
>>> l[-3]
'python'
>>> s[-1]
'n'

Check sequence using in operator

Following example keep you understand about in operator which can be used in control flows such as if, while loops.
if 'python' in list1:
 print 'it is in list1'
 
if 'perl' in list2:
 print 'it is in list2'

The str object type

String is a collection of charecter set. whoes index starts with 0. we can fetch the sub set of characters from the string, where in we can use slice operations on a string with start, end index values. We can also use the skip by value as third number
s[start:end:skip]

Strings are enclosed in single or double or truple quotation marks.
var1='Hello World!'
var2='Python Programming'
print 'var1[0]: ',var1[0]
print 'var2[0:6]:',var2[0:6]
print 'Updatestring:-',var1[:6]+'Python'
print var1*2
print "My name is %s and dob is %d"%('Python',1990)
s="I'm learning Python" #  
The following are SAMPLE CODE FOR STRING METHODS out of 40 methods available for strings. Check the str functions available as standard string object offers:
>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

Following are the experiments with some of str methods:
# first character capitalized in string
str1='guido van rossum'
print str1.capitalize()
print str1.center(30,'*') #30 is the total width of the string,'*' is the fill char
# count substrings in orginal string 
# count() contains 3 arguments 1.substring you want to search,2.search starts of the index,3.search ending of the index
# by default start and end takes zero and len-1 respectively
sub='s';
print 'str1.count(sub,0):-',str1.count(sub,0)
sub='van'
print 'str1.count(sub):-',str1.count(sub)
str1=str1.encode('base64','strict')
print 'Encoding string :'+str1
print 'Decode string :'+str1.decode('base64','strict')
# following method returns Ture if the string endswith specified suffix
str2='Guido van Rossum'
suffix='Rossum'
print str2.endswith(suffix)
print str2.endswith(suffix,1,17)
# find string in a existed string or not
str4='Van'
print str2.find(str4)
print str2.find(str4,17)
str5='sectokphb10k'
print str5.isalnum()
str6='kumar pumps'
print str6.isalnum()
print str4.isalpha()
str7='123456789'
print str7.isdigit()
print str6.islower()
print str2.islower()
str8='   '
print str8.isspace()

The list type

When you compare with C, Java we can store similar kind of data stored as a sequence called as arrays, where as in Python we have class list base functionality is similar to array but more powerful. It can hold the heterogeneous data into them. You can add the elements at the end or in the middle or replace the existing elements. These list objects uses index that starts with 0 same as str objects.
SAMPLE CODE FOR LIST METHODS
list1=['python','CPython','jython']
list1.append('Java')
print list1
list1.insert(2,'c++')
print list1
list2=['bash','perl','shell','ruby','perl']
list1.extend(list2)
print list1
 # reversing the list
list1.reverse()
print list1

# sorting the list
list2.sort() 
print list2
# count the strings in list
value=list2.count('perl')
print value
# Locate string
index=list1.index("jython")
print index,list1[index]

The tuple type

Tuple types are immutable ordered sequence of items. These items can be of mixed types, including collection types
#!/usr/bin/python
"""
This script illustrates the usage of tuple objects
and their methods, operations
"""

tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');

#Concatination of tuples
tup3 = tup1 + tup2;
print tup3;

#repeating tuple
print tup1*3

#Sys admin stuff with builtin tuple here
import os
ut=os.uname()
print "uname resulted a tuple:", ut
print "Operating System:",ut[0], "\nProcessor:", ut[len(ut)-1]
It is the experiment of fetching with tuple operations +, *, in. Excution gives the output as follows:
 ~/pybin$ ./tuple1.py
(12, 34.56, 'abc', 'xyz')
(12, 34.56, 12, 34.56, 12, 34.56)
uname resulted tuple: ('Linux', 'puppet', '3.8.0-36-generic', '#52~precise1-Ubun
tu SMP Mon Feb 3 21:56:56 UTC 2014', 'i686')
Operating System: Linux
Processor: i686
We will see Sets and Dictionaries in another post soon...

Sunday, July 6, 2014

Python Classes and Objects

******** OBJECT ORIENTED PROGRAMMING IN PYTHON ********

OBJECT: Objects are the basic run-time entities in an object-oriented system, They may represent a person, a place, a bank account, a table of data or any item that the program must handle.

CLASS: A class is a special data type which defines how to build a certain kind of object.The class also stores some data items that are shared by all the instances of this class
class student:
    “““A class representing a student ”””
 def __init__(self , n, a):        
   self.full_name = n     
   self.age = a
 def get_age(self):  #Method     
   return self.age

The following program shows the How to initialize the members in Class, How to create Instances for particular Object and finally How to print existed data

class Student:
# Initializing the variables
	def __init__(self,name,age):
		self.fullname=name
		self.sage=age
# Display the entered data such as Students name and age
	def display(self):
		print 'Student FullName: %s' %(self.fullname)
		print 'Stuent Age: %d'%(self.sage)
# S1,S2 and S3 objects 
# S1,S2 and S3 are three different student details and age
s1=Student('Python',14)
s1.display()
s2=Student('Jython',23)
s2.display()
s3=Student('Objects',45)
s3.display()

=== Encapsulation and Abstraction in Python ===

-> Encapsulate means to hide. Encapsulation is also called data hiding.You can think Encapsulation like a capsule (medicine tablet) which hides medicine inside it. Encapsulation is wrapping, just hiding properties and methods. Encapsulation is used for hide the code and data in a single unit to protect the data from the outside the world. Class is the best example of encapsulation. Abstraction refers to showing only the necessary details to the intended user. As the name suggests, abstraction is the "abstract form of anything". We use abstraction in programming languages to make abstract class. Abstract class represents abstract view of methods and properties of class. In programming languages, encapsulation is used to refer to one of two related but distinct notions, and sometimes to the combination thereof: A language mechanism for restricting access to some of the object's components. A language construct that facilitates the bundling of data with the methods (or other functions) operating on that data.

=== PUBLIC, PROTECTED AND PRIVATE MEMBERS BEHAVIOR ===

>>> x = Encapsulation(11,13,17) 
>>> x.public
 11 
>>> x._protected 
13 
>>> x._protected = 23 
>>> x._protected 
23 
>>> x.__private 
	Traceback (most recent call last): 
		File "", line 1, in 
	 AttributeError: 'Encapsulation' object has no attribute '__private‘
 >>> 

=== Inheritance in Python ===

The Python feature most often associated with object-oriented programming is inheritance. Inheritance is the ability to define a new class that is a modified version of an existing class. The primary advantage of this feature is that you can add new methods to a class without modifying the existing class. It is called inheritance because the new class inherits all of the methods of the existing class. Extending this metaphor, the existing class is sometimes called the parent class. The new class may be called the child class or sometimes subclass.

===== SAMPLE CODE FOR BASIC INHERITANCE =====

class Person(object):
	def __init__(self,name,age):
		self.name=name
		self.age=age
	def show(self):
		print 'Person Name: %s' %(self.name)
		print 'Person Age: %s' %(self.age)
class Employe(Person):
	def __init__(self,name,age,company,sal):
		self.company=company
		self.sal=sal
		super(Employe,self).__init__(name,age)
	def __repr__(self):
		return str (self.name+self.age+self.company+self.sal)
	def showme(self):
		super(Employe,self).show()
		print 'Company Name: %s'%(self.company)
		print 'Employe Salary per Annum: %s' %(self.sal)
		print '\n'
		
empdict={'guido':['45','PYTHON','500000'],'van':['25','JYTHON','200000'],'rossum':['35','ABC','400000']}
for key,value in empdict.iteritems():
	print key,value
	emp=Employe(key,value[0],value[1],value[2])
	emp.showme()

=== POLYMORPHISM in Python ===

Polymorphism is something similar to a word having several different meanings depending on the context. In object-oriented programming, polymorphism (from the Greek meaning "having multiple forms") is the characteristic of being able to assign a different meaning or usage to something in different contexts - specifically, to allow an entity such as a variable, a function, or an object to have more than one form. The classic example is the Shape class and all the classes that can inherit from it (square, circle, irregular polygon, splat and so on). With polymorphism, each of these classes will have different underlying data. A point shape needs only two co-ordinates (assuming it's in a two-dimensional space of course). A circle needs a center and radius. A square or rectangle needs two co-ordinates for the top left and bottom right corners (and possibly) a rotation. An irregular polygon needs a series of lines.

=====SAMPLE CODE FOR POLYMORPHISM =====

class Person:
    def __init__(self, name):    
        self.name = name
    def designation(self):              
        raise NotImplementedError("Subclass must implement abstract method")
class Employe(Person):
    def designation(self):
        return 'Software Engineer‘
class Doctor(Person):
    def designation(self):
        return 'Cardiologist‘
class Student(Person):
	def designation(self):
		return 'Graduate Engineer'
persons = [Employe('Guido Van Rossum'),Doctor('Chalapathi'),Student('Robert')]
for person in persons:
    print person.name + ': ' + person.designation()

DevOps Foundation course

DevOps Foundation course
Join us to learn DevOps from the Beginning