Python 101 - Introduction to Python - Part 3

by Dave Kuhlman
Wednesday, 3rd August 2005

Organization

This section describes Python features that you can use to organize and structure your code.

Functions

A basic function

Use def to define a function. Here is a simple example:

 

def test(msg, count):
for idx in range(count):
print '%s %d' % (msg, idx)

test('Test #', 4)

Comments:

 

A function with default arguments


Providing default arguments allows the caller to omit some arguments. Here is an example:

 

def testDefaultArgs(arg1='default1', arg2='default2'):
print 'arg1:', arg1
print 'arg2:', arg2

testDefaultArgs('Explicit value')

The above example prints:

 

arg1: Explicit value
arg2: default2

Argument lists and keyword argument lists

Here is an example:

 

def testArgLists_1(*args, **kwargs):
print 'args:', args
print 'kwargs:', kwargs

testArgLists_1('aaa', 'bbb', arg1='ccc', arg2='ddd')

def testArgLists_2(arg0, *args, **kwargs):
print 'arg0: "%s"' % arg0
print 'args:', args
print 'kwargs:', kwargs

print '=' * 40
testArgLists_2('a first argument', 'aaa', 'bbb', arg1='ccc', arg2='ddd')

Running this example displays:

 

args: ('aaa', 'bbb')
kwargs: {'arg1': 'ccc', 'arg2': 'ddd'}
========================================
arg0: "a first argument"
args: ('aaa', 'bbb')
kwargs: {'arg1': 'ccc', 'arg2': 'ddd'}

A little guidance:

 

Classes and Instances

A basic class

Define a basic class as follows:

 

class Basic:
def __init__(self, name):
self.name = name
def show(self):
print 'Basic -- name: %s' % self.name

obj1 = Basic('Apricot')
obj1.show()

Running the above example produces the following:

 

Basic -- name: Apricot

Explanation:

 

A few more notes on self:

 

Inheritance

Define a class Special that inherits from a super-class Basic as follows:

 

class Basic:
def __init__(self, name):
self.name = name
def show(self):
print 'Basic -- name: %s' % self.name

class Special(Basic):
def __init__(self, name, edible):
Basic.__init__(self, name)
self.upper = name.upper()
self.edible = edible
def show(self):
Basic.show(self)
print 'Special -- upper name: %s.' % self.upper,
if self.edible:
print "It's edible."
else:
print "It's not edible."
def edible(self):
return self.edible

obj1 = Basic('Apricot')
obj1.show()
print '=' * 30
obj2 = Special('Peach', 1)
obj2.show()

Running this example produces the following:

 

Basic -- name: Apricot
==============================
Basic -- name: Peach
Special -- upper name: PEACH. It's edible.

Commentary:

 

Class data

A class data member is a member that has only one value for the class and all its instances. Here is an example from the Python FAQ at http://www.python.org/doc/FAQ.html:

 

class C:
count = 0 # number of times C.__init__ called
def __init__(self):
C.count = C.count + 1
def getcount(self):
return C.count # or return self.count

c1 = C()
print 'Current count:', c1.getcount()
c2 = C()
print 'Current count:', c2.getcount()

Running this example produces:

 

Current count: 1
Current count: 2

Static Methods and class methods

Here is an example that shows how to define static methods and class methods:

 

class Advanced:
def __init__(self, name):
self.name = name
def Description():
return 'This is an advanced class.'
def ClassDescription(cls):
return 'This is advanced class: %s' % repr(cls)
Description = staticmethod(Description)
ClassDescription = classmethod(ClassDescription)

obj1 = Advanced('Nectarine')
print obj1.Description()
print obj1.ClassDescription()
print '=' * 30
print Advanced.Description()
print Advanced.ClassDescription()

Running the above produces the following output:

 

This is an advanced class.
This is advanced class: <class __main__.Advanced at 0x401c926c>
==============================
This is an advanced class.
This is advanced class: <class __main__.Advanced at 0x401c926c>

Notes:

 

You should also review the relevant standard Python documentation which you can find at Python Library Reference - 2.1 Built-in Functions.

By now, you are likely to be asking: ``Why and when should I use class methods and static methods?'' Here is a bit of guidance, though

 

To summarize:

 

Modules

You can use a module to organize a number of Python definitions in a single file. Here is an example:

 

# python_101_module_simple.py

"""
This simple module contains definitions of a class and several
functions.
"""

LABEL = '===== Testing a simple module ====='

class Person:
"""Sample of a simple class definition.
"""
def __init__(self, name, description):
self.name = name
self.description = description
def show(self):
print 'Person -- name: %s description: %s' % (self.name, self.description)

def test(msg, count):
"""A sample of a simple function.
"""
for idx in range(count):
print '%s %d' % (msg, idx)

def testDefaultArgs(arg1='default1', arg2='default2'):
"""A function with default arguments.
"""
print 'arg1:', arg1
print 'arg2:', arg2

def testArgLists(*args, **kwargs):
"""
A function which references the argument list and keyword arguments.
"""
print 'args:', args
print 'kwargs:', kwargs

def main():
"""
A test harness for this module.
"""
print LABEL
person = Person('Herman', 'A cute guy')
person.show()
print '=' * 30
test('Test #', 4)
print '=' * 30
testDefaultArgs('Explicit value')
print '=' * 30
testArgLists('aaa', 'bbb', arg1='ccc', arg2='ddd')

if __name__ == '__main__':
main()

Running the above produces the following output:

 

===== Testing a simple module =====
Person -- name: Herman description: A cute guy
==============================
Test # 0
Test # 1
Test # 2
Test # 3
==============================
arg1: Explicit value
arg2: default2
==============================
args: ('aaa', 'bbb')
kwargs: {'arg1': 'ccc', 'arg2': 'ddd'}

Comments:

 

Packages

A package is a way to organize a number of modules together as a unit. Python packages can also contain other packages.

To give us an example to talk about, consider the follow package structure:

 

package_example/
package_example/__init__.py
package_example/module1.py
package_example/module2.py
package_example/A.py
package_example/B.py
</div>
And, here are the contents:
 
<div class="verbatim"># __init__.py

# Expose definitions from modules in this package.
from module1 import class1
from module2 import class2

# module1.py

class class1:
def __init__(self):
self.description = 'class #1'
def show(self):
print self.description

# module2.py

class class2:
def __init__(self):
self.description = 'class #2'
def show(self):
print self.description

# A.py

import B

# B.py

def function_b():
print 'Hello from function_b'

In order to be used as a Python package (e.g. so that modules can be imported from it) a directory must contain a file whose name is __init__.py. The code in this module is evaluated the first time a module is imported from the package.

In order to import modules from a package, you may either add the package directory to sys.path or, if the parent directory is on sys.path, use dot-notation to explicitly specify the path. In our example, you might use: "import package_example.module1".

A module in a package can import another module from the same package directly without using the path to the package. For example, the module A in our sample package package_example can import module B in the same package with "import B". Module A does not need to use "import package_example.B".

You can find additional information on packages at http://www.python.org/doc/essays/packages.html.

Suggested techniques:

 

A few additional notes:

 


Dave Kuhlman has worked for many years on a variety of software development projects, in several programming languages, and on more than one platform. Because of Python's clear syntax, developer friendliness, and broad utility, Dave focuses his energy on the Python language, on systems built with Python, and on developing documentation and training materials for those systems. Dave's current work involves XML processing in Python as well as the development of tools and documentation for Zope and the CMSs (content management systems) that run on top of Zope, Dave's current platform is Debian GNU/Linux; he has installed and administers a small network composed of several Linux boxes behind a Linux router/gateway. More information about Dave's work can be found at http://www.rexx.com/~dkuhlman.
View the original article Python 101 - Introduction to Python - Part 3