Scripting > Scripting Basics


Modules, Functions and Methods

A function is a procedure which takes zero or more parameters, performs some action, optionally modifies one or more of the parameters and optionally returns a value or sequence of values.

 

A class is the definition of a type of object.  All objects of that type (class) have the same definition and thus have the same attributes and behavior.  Classes may define functions that apply to individual objects of that type.  These functions are called methods.

 

An object is an instance of a class, which behaves in the way defined by the class, and has any methods defined by the class.

 

Python provides many functions and classes by default.  In our examples, we have used functions len() and range() which Python provides by default.  We have also used the classes list and string, which Python also provides by default.  We didn’t use any methods of the class list, but we used the string method index() in example 7 (string_1.index(“debug”) != -1).  It is important to note that the object method index() doesn’t apply to the string class in general, but to the specific string object string_1.

 

There are other functions and classes which Python does not provide by default.  These functions and classes are grouped into modules according to their common purpose.  Examples of modules are “os” for operating system functions and “socket” for socket-based network functions.  Before any of the functions or classes in a module can be accessed, the module must be imported with the import statement, which has the syntax:

 

from module import *

 

Other methods of using the import statement are specified in Python tutorials and references listed at the official Python website: www.python.org.  In the Jython implementation, Java packages can be imported as if they were Python modules, and the Java package java.lang is imported by default.

 

Example: Using a Function from an Imported Module


# use the getcwd() function in the os module to get

# the current working directory

 

from os import *

cwd = getcwd()

 

A module does not have to be imported in order to work with objects of a class defined in that module if that object was returned by a function or method already accessible.  For example, the Python module “string” does not have to be imported to call methods of string objects, but does have to be imported to access string functions.