An Introduction to Python
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']
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”.
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.
Sponsored by AMD
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.
Sponsored by DLT Solutions
| Designing Electronics with Linux | May 22, 2013 |
| Dynamic DNS—an Object Lesson in Problem Solving | May 21, 2013 |
| Using Salt Stack and Vagrant for Drupal Development | May 20, 2013 |
| Making Linux and Android Get Along (It's Not as Hard as It Sounds) | May 16, 2013 |
| Drupal Is a Framework: Why Everyone Needs to Understand This | May 15, 2013 |
| Home, My Backup Data Center | May 13, 2013 |
- Designing Electronics with Linux
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- Dynamic DNS—an Object Lesson in Problem Solving
- Using Salt Stack and Vagrant for Drupal Development
- Build a Skype Server for Your Home Phone System
- New Products
- Validate an E-Mail Address with PHP, the Right Way
- Why Python?
- A Topic for Discussion - Open Source Feature-Richness?
- Tech Tip: Really Simple HTTP Server with Python
Enter to Win an Adafruit Pi Cobbler Breakout Kit for Raspberry Pi

It's Raspberry Pi month at Linux Journal. Each week in May, Adafruit will be giving away a Pi-related prize to a lucky, randomly drawn LJ reader. Winners will be announced weekly.
Fill out the fields below to enter to win this week's prize-- a Pi Cobbler Breakout Kit for Raspberry Pi.
Congratulations to our winners so far:
- 5-8-13, Pi Starter Pack: Jack Davis
- 5-15-13, Pi Model B 512MB RAM: Patrick Dunn
- 5-21-13, Prototyping Pi Plate Kit: Philip Kirby
- Next winner announced on 5-27-13!
Free Webinar: Hadoop
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.
Some of key questions to be discussed are:
- What is the “typical” Hadoop cluster and what should be installed on the different machine types?
- Why should you consider the typical workload patterns when making your hardware decisions?
- Are all microservers created equal for Hadoop deployments?
- How do I plan for expansion if I require more compute, memory, storage or networking?




41 min 4 sec ago
49 min 5 sec ago
3 hours 3 min ago
5 hours 33 min ago
15 hours 36 min ago
20 hours 3 min ago
23 hours 39 min ago
1 day 11 min ago
1 day 2 hours ago
1 day 2 hours ago