Python Quick Notes :: Part - 2
Bhaskar S | 02/16/2013 |
Hands-on With Python - II
User defined functions in Python are used for defining a block of reusable code and have the following syntax:
def function-name(parameter-list): docstring function-body return value
where:
function-name - is the name of the user-defined function
parameter-list - is a comma separated list of function parameters. This is optional
docstring - is a string to document what the function does. This is optional
function-body - is the block of reusable Python code
return value - is for exiting the user-defined function with an optional value to be passed back to the caller
Important facts about user-defined functions in Python:
Parameters are passed by reference
Variables defined inside a user-defined function are local in scope
To access a variable defined outside the user-defined function, use the global keyword
A parameter can be optionally be provided with a default parameter value
The following is the python program named sample-07.py:
Execute the following command:
python sample-07.py
The following is the output:
sum(10) = 55 a (before mutate(a)) = [1, 2, 3, 4, 5] a (after mutate(a)) = [2, 4, 6, 8, 10] b (before localvar()) = hello python b (inside) = Python b (after localvar()) = hello python b (before globvar()) = hello python b (inside) = HELLO PYTHON b (after globvar()) = HELLO PYTHON c (before defval(c, 4)) = [1, 2, 3, 4, 5] c (after defval(c, 4)) = [4, 8, 12, 16, 20] d (before defval(d)) = [1, 2, 3, 4, 5] d (after defval(d)) = [3, 6, 9, 12, 15]
A Python module is a regular Python code file containing functions and related objects. The following are some facts about Python modules:
A module name is the same as the module file name. For example, if the module file name is MyMath.py, then the module name is MyMath
To use a Python module, use the import keyword followed by the module name. For example, import MyMath
To access any object or function from a module, use the syntax: modulename.object or modulename.function(parameters). For example, to access the function summation() from our example module MyMath, we use the MyMath.summation()
Python will try to search and locate the module file in the following order:
The current directory
In all the directories specified in the environment variable PYTHONPATH
In the default Python installation directory
The built-in function dir(modulename) returns the list of all the symbols including names of objects and functions for the specified module
The following is the python module named MyMath.py:
The following is the python program named sample-08.py that uses the module MyMath:
Execute the following command:
python sample-08.py
The following is the output:
dir(MyMath) = ['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'factorial', 'fibonacci', 'summation'] MyMath.summation(10) = 55 MyMath.factorial(10) = 3628800 MyMath.fibonacci(10) = 89
Python standard library comes with many modules and in the following we will mention only a few:
math - defines variables and functions to perform mathematical operations. The following are few examples:
math.pi - represents the mathematical constant PI whose value is 3.141592...
math.sqrt(n) - returns the square root of the number n
math.factorial(n) - returns the factorial of the number n
os - defines functions that allow to interact with the underlying operating system. The following are few examples:
os.getcwd() - returns the current working directory
os.mkdir(d) - create the specified directory d
os.rmdir(d) - remove the specified directory d
os.stat(fd) - returns information on the specified file or directory fd
re - defines functions to perform regular expression matches and searches. The following is an example:
re.match(p, s) - returns a match object if there is a match of the specified pattern p in the specified text s
sys - defines variables and functions that provide access to different aspects of the Python runtime environment. The following are few examples:
sys.argv - represents the list of command line arguments passed to a Python program
sys.platform - returns the underlying operating platform identifier
sys.path - returns the list of directories where Python will search for modules
The following is the python program named sample-09.py that uses some of the above mentioned standard modules:
Execute the following command:
python sample-09.py
The following is the output:
---> Module sys operations arg[0] = sample-09.py arg[1] = Hello arg[2] = Python Operating platform: linux2 Module search path: ['/home/bswamina/Projects/Python', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-linux2', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PIL', '/usr/lib/python2.7/dist-packages/gst-0.10', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.7'] Module list: ['copy_reg', 'sre_compile', '_sre', 'encodings', 'site', '__builtin__', 'sysconfig', '__main__', 'encodings.encodings', 'abc', 'posixpath', '_weakrefset', 'errno', 'encodings.codecs', 'sre_constants', 're', '_abcoll', 'types', '_codecs', 'encodings.__builtin__', '_warnings', 'math', 'genericpath', 'stat', 'zipimport', '_sysconfigdata', 'warnings', 'UserDict', 'encodings.utf_8', 'sys', 'codecs', '_sysconfigdata_nd', 'os.path', 'sitecustomize', 'signal', 'traceback', 'linecache', 'posix', 'encodings.aliases', 'exceptions', 'sre_parse', 'os', '_weakref'] ---> Module math operations Pi: 3.14159265359 math.sqrt(75): 8.66025403784 ---> Module os operations Current working directory: /home/bswamina/Projects/Python Create directory TEMP ... Size of directory TEMP: 4096 Remove directory TEMP ... Execute ls -l ... total 44 -rw-r--r-- 1 bswamina bswamina 631 Feb 16 17:32 MyMath.py -rw-r--r-- 1 bswamina bswamina 957 Feb 16 17:35 MyMath.pyc -rw-r--r-- 1 bswamina bswamina 1843 Feb 10 16:00 sample-01.py -rw-r--r-- 1 bswamina bswamina 1035 Feb 10 16:30 sample-02.py -rw-r--r-- 1 bswamina bswamina 951 Feb 10 17:07 sample-03.py -rw-r--r-- 1 bswamina bswamina 1400 Feb 10 17:58 sample-04.py -rw-r--r-- 1 bswamina bswamina 835 Feb 10 18:10 sample-05.py -rw-r--r-- 1 bswamina bswamina 719 Feb 10 20:42 sample-06.py -rw-r--r-- 1 bswamina bswamina 1645 Feb 15 23:16 sample-07.py -rw-r--r-- 1 bswamina bswamina 408 Feb 16 20:09 sample-08.py -rw-r--r-- 1 bswamina bswamina 1484 Feb 16 22:07 sample-09.py ---> Module re operations First word: Hello Day = 16, Month: Feb, Year: 2013
Python is an object oriented language and hence allows us to defined object classes. A class is nothing more than an encapsulation of data and related functions. The following are some facts about Python classes:
Functions inside a class are referred to as methods
The Python variable self is similar to the variable this in other programming languages like C++ or Java
The first parameter of every method in a class has to be self. This has to be explicitly specfied at the time of method definition. Python implicitly adds it when the method of a class is invoked
The method __init__(self) is the initializer method (also known as the constructor in languages like C++ or Java) of a class and is automatically invoked when a new instance of the class is created. In the __init__ method is where one defines and initializes the data attributes of the class
The following is the python program named sample-10.py that defines and uses the Python class Contact:
Execute the following command:
python sample-10.py
The following is the output:
John's Email = john@space.com John's Home = 111-222-3333 John's Mobile = 999-888-7777
Some more facts about Python classes:
A class variable is shared by all instances of the class and is defined in the class outside of the methods
The visibility of all data attributes and methods is public in Python. Python does not have the concept of public, protected, or private access types for instance variable unlike programming languages C++ or Java
The built-in class variable __name__ refers to the class name
The built-in class variable __doc__ refers to the class documentation
Python uses automatic garbage collection to reclaims memory by deleting objects that no longer referenced
The method __del__(self) is the destructor of a class and is called when Python is about to delete an instance of the class
The method __str__(self) is the method toString() in Java
The following is the python program named sample-11.py:
Execute the following command:
python sample-11.py
The following is the output:
Account.INTEREST = 0.75 Account.__name__ = Account Account.__doc__ = This class encapsulates account information. It has two instance variables - acctNo and balance. It also defines a class variable INTEREST. It defines methods - credit(), debit(), and getBalance() *** Account [12345], Balance: 100.0 ---> Credit of 25 Balance after credit: 125.0 ---> Debit of 50 Balance after debit: 75.0 Account [ 12345 ] will be deleted
Python supports class inheritance. The following is the python program named sample-12.py will demonstrate class inheritance:
Execute the following command:
python sample-12.py
The following is the output:
Base.__init__(), m = 10 b.getM() = 10 Derived.__init__(), m = 10 , n = 20 Base.__init__(), m = 10 d.getM() = 10 d.getN() = 20
References