Tuesday, January 15, 2013

Python Fundamentals (Functions, Classes, Objects, and Exceptions)

Functions allow sections of code to be grouped better as per functionality:

#!/usr/bin/env python

import sys

def print(printLines):

        for count in range(0,10) :
                print printLines

print(sys.argv[1])

Class example:

#!/usr/bin/env python

class Calculator:

        #constructor of the class
        def __init__(self, ina, inb):
            self.a = ina
            self.b = inb

        # define routine
        def add(self):
            return self.a + self.b

        def mul(self):
            return self.a*self.b

# Example of Class Inheritence
class Scientific(Calculator) :

        def power(self):
        # Power and logarithmic functions
            return pow(self.a, self.b)
        def quickAdd(a,b):
            return a+b

# Calling the classes to print to screen
newCalculation = Calculator(10, 20)

print 'a+b: %d'%newCalculation.add()
print 'a*b: %d'%newCalculation.mul()

newPower = Scientific(2,3)

print 'a+b: %d'%newPower.add()
print 'a*b: %d'%newPower.mul()
print 'a pow b: %d' %newPower.power()

Exception Handling by using the "ZeroDivisionError" object:


>>> try :
...     a = 0/0
... except Exception as im:
...     print im
...
integer division or modulo by zero

To see the help page for the "im" object, type:
>>> help(im)

No comments:

Post a Comment