An Introduction to Python

Python is an extensible, high-level, interpreted, object-oriented programming language. Ready for use in the real world, it's also free.
Python Has Real Class

With the next example, I'll try to demonstrate some of these features. The StackingThings class will allow the user to stack items on top of each other until a breaking point is reached.


1       #!/usr/local/bin/python
2
3       StackingException = `StackingException'
4
5       class StackingThings:
6       names = (`llama', `spam', `16 ton weight',
7       `dead parrot')
8       weights = {}
9       weights[`llama']         =     300
10      weights[`spam']          =       1
11      weights[`16 ton weight'] =   32000
12      weights[`dead parrot']   =       2
13      breakpt = {}    # breaking points
14      breakpt[`llama']         =     200
15      breakpt[`spam']          =    1000
16      breakpt[`16 ton weight'] = 1000000
17      breakpt[`dead parrot']   =      15
18
19      def _ _init_ _(self):
20      self.items_stacked = []
21      def add(self, item):
22              if item not in self.names:
23                      raise StackingException, \
24                              item+`not a stackable object'
25      self.items_stacked.insert(0, item)
26      try:
27              self.test_strength(item)
28                except StackingException, val:
29                      print item, val
30      def test_strength(self, item):
31          wt = 0
32          bp = 1000000
33          for i in self.items_stacked:
34              wt = wt + self.weights[i]
35              if wt > bp:
36                 self.items_stacked.remove(item)
37                 raise StackingException, \
38                    `exceeds breaking point!'
39              bp = self.breakpt[i]
40
41      # user code to test StackingThings class
42
43  s = StackingThings()
44
45  s.add(`llama')
46  s.add(`spam')
47  s.add(`spam')
48  s.add(`spam')
49  s.add(`dead parrot')
50  s.add(`16 ton weight')
51
52  print `items stacked = ', s.items_stacked
53
54  try:
55      s.add(`bad object')
56  except StackingException, msg:
57      print `exception:', msg

This script produces the following output:

16 ton weight exceeds breaking point!
items stacked =  [`dead parrot', `spam', `spam',
     `spam', `llama']
exception: bad object not a stackable object

The StackingThings class itself consists of 3 methods: _ _init_ _(), add(), and test_strength(). When initiating StackingThings, we use the special __init__ method to create its initial state by initializing the list of stacked items: items_stacked = []. The add() method is essentially the only method that is accessed by the user of StackingThings. And test_strength() is called by add() to verify that we have not exceeded our breaking point.

The first argument to each method in our example is called self. This is just a convention, but it makes our code much more readable. The first argument to a Python method is used in a somewhat similar fashion as this keyword in C++.

Python provides for exception handling, both built-in (i.e. ZeroDivisionError, TypeError, NameError, etc.) and user-defined exceptions. The latter is especially useful in developing robust classes. Python uses the try/except syntax for exception handling:

try:
    DenominateZero()
except ZeroDivisionError, val:
    print `Whoops:', val

Our add() method is used to try an exception in test_strength() and raise an exception when we pass it an illegal stacking item.

Two of the built-in methods for Python lists that are demonstrated in the example on lines 25 and 36 are insert() and remove(). Other supported operations on list objects include append(), count(), index(), reverse(), and sort().

The data attributes may be accessed by the methods of the class as well as the user code: Either print self.names (within a class method) or print s.names (from the user code) will print the list of legal stacking things:

[`llama', `spam', `16 ton weight', `dead parrot']
Look It Up!

Dictionaries (associative arrays to all you awk/perl hackers) are one of the most useful Python data types. Unlike a normal array, which is indexed by number, associative arrays are indexed by strings. The value of this utility is worth describing in some detail.

I frequently deal with ICD-9-CM codes in medical applications. These codes are usually numeric, but sometimes alphanumeric. They usually have a decimal point, but sometimes don't. Some of the codes may be further sub-divided into additional ICD-9 codes. Furthermore, codes are added and deleted periodically, but most don't change. Normally, the lookup of ICD-9 codes will be done in a relational database, but it is also convenient to use small data sets within an application. For example, given the dictionaries icd9 and subdivide:

   x              subdivide[x]          icd9[x]
  ---             ------------    -------------------------
  `692'                 1         `Contact dermatitis'
  `692.0'               0         `Due to detergents'
  `692.2'               0         `Due to solvents'
  `692.7'               1         `Due to solar radiation'
  `692.70'              0         `Unspecified dermatitis'
  `692.71'              0         `Sunburn'
  `692.72'              0         `Other: Photodermatitis'

We can manipulate the ICD-9 codes in the following manner:

for code in icd9.keys():
  if subdivide[code]:
      print `ICD-9',code,'may be further subdivided'
        else:
      print `Description for',code,`is:',icd9[code]

This would produce the following output:

ICD-9 692.7 may be further subdivided
Description for 692.70 is: Unspecified dermatitis
Description for 692.0 is: Due to detergents
ICD-9 692 may be further subdivided
Description for 692.71 is: Sunburn
Description for 692.2 is: Due to solvents
Description for 692.72 is: Other: Photodermatitis

Lines 8-17 of our StackingThings example use dictionaries, but the initialization was broken into several lines for clarity. This could be reduced to:

weights = {`llama':300, `spam':1, \
    `16 ton weight':32000, `dead parrot':2}
breakpt = {`llama':200, `spam':1000, \
    `16 ton weight':1000000, `dead parrot':15}

Finally, inheritance is provided in Python, although it is not demonstrated in this example. The derived class may override methods of its base class or classes (yes, multiple inheritance is supported in a limited form). In C++ parlance, all methods in a Python class are “virtual”.

______________________

Webcast
How to Build an Optimal Hadoop Cluster to Store and Maintain Unlimited Amounts of Data Using Microservers

Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.

Learn More

Sponsored by AMD

White Paper
Red Hat White Paper: Using an Open Source Framework to Catch the Bad Guy

Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6

Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.

Learn more about catching the bad guy in this free white paper.

Learn More

Sponsored by DLT Solutions