Tuesday, November 20, 2012

Part 6 - Python Functions and Classes

Last but not least, even though python is a very simple language to learn, it is quite powerful in the sense that it supports complex functions and object oriented structures of classes.
In Part 6, we will briefly discuss python Functions and Classes.

Python Functions

When you want to group a bunch of actions together, to recall them by name later, you can create a function, give it a name, and pass it some parameters if needed. After using the given parameters, and processing them as needed. The function will returns a resulting object that you then use for your next steps.
The function always starts with the def marker, then the functionname, followed by the parameters in parenthesis and ending with the colon (:). The next line must be indented to indicate that it is the body of the function. The keyword return, will return the resulting expression that the function is supposed to spit back out to the calling statement.

 

Example of a function: fibonacci sequence generator

 

This script is a function that will produce the sequence of fibonacci sequence numbers

Python Class

     A Class is a user-defined prototype for an object that defines a set of attributes that characterize any object of the class.
Class attributes are data members (class variables and instance variables) and methods, accessed via dot notation.  


 
In this example, the class definition begins with the key word class. Followed by the class name Employee with colon (:) at the end. The following lines of the class block must be indented and aligned. The __init__ function is used to create instances of the class object.
use def to define other methods of the class. Data attributes can be assigned as local variables.
The python class is also capable of inherting properties and methods from other classes. But we won't go into that level of details here just yet.