Chapter 1. Jython Overview

CONTENTS
  •  Programming, Briefly
  •  Learning Python First
  •  Python the Language
  •  Starting with Python
  •  Basic Functions with Python
  •  Python as a Main Program
  •  The Fast Track
  •  The Power of Python
  •  Where Do You Go from Here?
  •  Summary

Terms in This Chapter

  • Applet

  • Boolean value

  • Bytecode

  • Class

  • Compiler

  • Concatenation

  • Control flow

  • Expression

  • Floating-point number

  • for loop

  • Function

  • Immutability

  • Index/Indexing

  • Interactive mode

  • Interpreter

  • Iteration

  • Macro

  • Main method

  • Method

  • Module

  • Object

  • Programming

  • Pseudocode

  • Script

  • Sequence

  • Servlet

  • Slice notation

  • Statement

  • String

  • Syntax

  • Type

  • Value

  • Variable

In this chapter you will learn just what Python programming is and how to save and run Python scripts.

Programming, Briefly

You may have programmed a computer without even knowing it. For example, have you ever written or recorded a spreadsheet macro (or any other macro for any type of application)? If you have, you've programmed. Of course, programming is a lot more complicated than writing macros; still, many people are overly apprehensive when it comes to learning this skill.

You're going to find out that there's often not much difference between a macro or a scripting language and "real" programming. However, macro and script don't intimidate novice users, whereas programming does. The point is that learning programming doesn't have to be hard. In fact, the hardest part about it is having the right attitude. If you believe you can't learn to program, you probably won't.

At its most basic level, programming is instructing the computer, in a language that it understands, so that it can perform tasks. Like any language you learned in high school, a programming language has a vocabulary, grammar, syntax, punctuation, and parts of speech. The trick is knowing how to use these components correctly so that you get your point across and the job gets done.

Consider this very simple instruction:

write("Hello World")

Called a statement, it's the primary building block of programming. It "invokes," or "calls," the write function.

A function is a grouped set of statements. Within a program, one function can perform a task in its entirety, but more likely it will call another function, which in turn can call other functions, and so on, all of which together organize the program's statements. Remember being told in English class to organize your thoughts into a cohesive whole to get your point across? This is what statements and functions do in computer languages.

Languages like Python need an interpreter to translate a human-generated program into a "machine-readable" form that the computer can understand. Other languages, such as C and C++, use a compiler. The difference between the two is that the compiler saves the translated code on the machine, allowing it to be run independently on another occasion, whereas the interpreter holds it in memory only for the duration of the program running when the translation was made. The upshot is that compiled programs are faster than interpreted programs.

Learning Python First

Learning any one programming language makes it much easier to understand not only computers but other programming languages as well. As you'll see, Python is perhaps the easiest language to learn and use. This makes it the logical one to get under your belt as a first step on the way to Visual Basic, Java, and so forth.

It's important to understand that not all languages are alike. For example, some, such as C++, Java, and Python, are terse. That is, they get a lot done without a lot of code. Others, like Assembly, are verbose. They need many lines of code to perform a simple task. To illustrate, let's pretend we're asking a computer to tell us how to get to downtown Phoenix, Arizona. Python would tell us to take Speedway Boulevard to I-10 and head west. Here's what Assembly would say:

  1. Walk to your garage.

  2. Open the garage door.

  3. Walk to the driver's side of the car.

  4. Put the key in the door.

  5. Unlock the door.

  6. Sit in the driver's seat

You get the picture.

Assembly language needs to be verbose because it does its heavy lifting in building core operating system parts and high-speed optimized programs. Most programs don't require a low-level draft horse like Assembly, however, but a high-level language that offers greater productivity.

A higher-level language abstracts (i.e., hides) the complexity of a lower-level language. It looks at the bigger picture and omits the details, as we saw in how Python and Assembly tell us how to get to Phoenix. The tradeoff is that a lower-level language is friendlier to the computer it can run faster whereas a higher-level language is friendlier to the programmer she can program faster. There's a hierarchy of complexity with programming languages: C and C++ are higher level than Assembly; Java is higher level than C++; and Python is higher level than Java. The higher the level, the greater the ease of use. The goal is making a language easy to use without draining its power.

Python the Language

Python is a dynamic object-oriented language (i.e., flexible) for writing applications, Java applets and servlets, and the like. (We'll learn more about applets in Chapter 18.) It has a close relationship with Java. In fact, it can do pretty much anything Java can because it compiles to Java and uses the Java class libraries. With Python, you can create animated Web pages, automate monotonous jobs, and write Internet-interactive programs.

Java and Python

No doubt you've heard of Java, even the novices among you. Over a thousand books on it are on bookstore and library shelves, so it's hard to miss.

Remember our discussion of compilers and interpreters? Like Python, Java is an interpreted language, but, like C++, it's also a compiled language. In other words, it compiles into an intermediate language called bytecode, which is then interpreted into machine code at runtime (that is, when the program is put to use by the user). This makes Java a hybrid; its ability to be both interepreted and compiled gives it flexibility as well as speed.

Java is popular among programmers because of its versatility and because it's a much easier language than C++. Still, it's a far cry from Visual Basic in the simplicity department. In fact, its complexity, along with its client-side speed and graphics problems, has allowed other languages, such as DHTML (that is, HTML combined with VBScript and/or JavaScript), to lure a substantial number of developers away from the Java camp.

None of this means that Java doesn't have the potential to become an excellent client-side development tool. I believe it does, and I program in it professionally. However, it doesn't fill the need for a higher-level scripting language that's easy on the programmer, and this is where Python comes in. Unlike Java, Python is easy enough for beginning programmers to master quickly and yet powerful enough to keep experienced programmers interested.

Jython

Because of the success of Java, it made sense to make Java and Python compatible. Thus, one version of Python, called Jython, has been ported to Java and so can compile to bytecode. This move will likely make Python the next Internet development phenomenon, like Java or XML. At the least, it will make it available to a much broader audience and make it applicable in more environments. Consider, for example, that Jython makes it much easier to add user-defined types in Java. (Don't worry, types will be explained in due time.)

The Object Management Group (OMG) has adopted Python as one of the scripting component languages of CORBA, a standard distributed object model. In fact, CorbaScript, which is also a standard script, is one of Python's close cousins. Python also works with ActiveX (also known as COM+), a nonstandard distributed component model that ships with Windows operating systems, and with JavaBeans and RMI, which is a distributed object model for Java applications. With the addition of the OMG's CORBABean specification, which effectively gives CORBA a client-side tool-able component model, Python can be used to script CORBA objects as well.

The reason Python works so well with JavaBeans, ActiveX, and CORBA is that these products are all component models, that is, ways to manufacture components. Python serves as a means to wire together, or "glue," purchased or built components into an application. At the moment, Visual Basic is the de facto standard for scripting together ActiveX components into applications, but it's limited to Windows platforms. Python is becoming the standard for scripting together components from CORBA, JavaBeans, Enterprise JavaBeans, and ActiveX.

For Programmers and Novices: Jython Focus

Our focus will be primarily on Jython, rather than on CPython (the non-Java version). Either Jython or CPython can be used for an understanding of the core aspects of Python, but you'll definitely need the Java version when we get to JFC/Swing, applets, and the like.

You know the old saying "Every journey begins with the first step." Let's take that first step now.

Starting with Python

To install Python you must have a recent version of the Java Development Kit (JDK). For installation details, refer to Appendix A.

Now you're up and running. I'm going to assume that you're sitting at the keyboard with this book situated so that you can follow along with the interactive sessions. This is critical even if you don't understand the topic under discussion. Once again, the only way to learn programming is to program, even if you're not sure what you're doing. Don't worry; you soon will.

Python Interactive Mode

This section explains how to use Python in interactive mode, that is, the user and Python interacting one instruction at a time. It's a great way to learn the language. Also explained are the essential features of Python, including simple statements, expressions, and data types.

To get Python going, at the DOS prompt (or the equivalent for your operating system) type Python (for CPython) or Jython (for the Java-enabled version). You should see a welcome message showing the Python version number and a copyright notice.

C:\Jython>jython Jython 1.1 on jdk1.3 Copyright 1997-1998 Corporation for National Research Initiatives >>>

This is followed by a prompt for your first command, known as the primary prompt and denoted by >>>. If you enter print "Hello World" here and then hit the Enter key, Python will obey your command and print "Hello World" to the monitor.

>>> print "Hello World" Hello World >>>

If that's all you want Python to do at this point, you can exit the system with another command.

>>>raise SystemExit

This creates what's known as an "exception" (we'll go into exceptions in Chapter 7), which gets you out of Python. Another way to exit is to hit the Ctrl key in combination with whichever key your system designates for leaving a session. On Windows this is usually Ctrl-z; on UNIX it's usually Ctrl-d.

Basic Functions with Python

The following sections cover how Python deals with the raw material of programming: numbers and text.

Numbers

Python can serve as a simple calculator. The syntax it uses is nearly identical to that used for writing spreadsheet formulas. For novices who've created spreadsheets, all of this will seem familiar. The same is true for programmers who've worked with any language that uses an algebraic syntax, such as Pascal, Fortran, Basic, C, or Java.

In Python, you enter a mathematical formula (called an expression) just as you do with spreadsheets, and you're given a resulting value. In programming terms, an expression is a Python statement that returns a value. That value is printed to the console.

Python's expression syntax is straightforward. The addition (+), subtraction ( ), multiplication (*), and division (/) operators work just like they do in spreadsheets and other programming languages. Parentheses work similarly as well, for grouping.

>>> (2*2)/4 1

The equal sign (=) assigns a value to a variable. In the first line of the following example, the variable is annual_salary, to which we assign a value of 20000. (My convention is to join two-word variable names with an underscore.)

>>> annual_salary = 20000 >>> monthly_salary = annual_salary/12 >>> monthly_salary 1666 >>> bosses_salary = annual_salary * 3 >>> bosses_salary 60000

In the second line, we divide annual_salary by 12 to arrive at a value for the variable monthly_salary. Then, in the third line, we enter monthly_salary at the prompt, which tells Python to print the value of that variable to the console. We can use annual_salary again in assigning a value to bosses_salary.

For Programmers: Implicit Variable Declaration

In Python variables are implicitly declared. That is, the first time a variable is used it is assigned a value. This assigned value determines its type. In the salary example, all variables are assigned values of type Integer.

Novices, if you're reading this note and are confused by the concept of type, don't worry; we'll get to it. For understanding the ideas presented in the rest of the chapter, you just need to know that numbers can be of type Integer; text can be of types String, List, etc. Basically, the type assigned to a variable tells Python what values it can have and what operations can be performed on it.

The values assigned to the variables we've seen so far have been whole numbers. Python can also work with decimals, known in programming as floating-point numbers (of type Float).

>>> sum=1.3 + 1.4 + 1.56 + 1.7 + 1.2 + 1.9 >>> mean = sum /6 >>> mean 1.51 >>>

In the first line, we create a variable called sum and assign as its value the result of adding six floating-point numbers. In the second line, we create a new variable called mean, to which we assign as its value the value of sum divided by 6. In the third line, we enter the variable mean, and Python displays its value to the console.

Text

Python, like all programming languages, works with text as strings of characters; individual strings are delimited by quotes. Take a look at the following code example:

>>> Name = "James Agular" >>> HelloGreeting = "Hello " + Name + ", how are you?" >>> print HelloGreeting Hello James Agular, how are you? >>>

In the first line, we create a variable called Name and assign as its value the string "James Agular". In the second line, we create a variable called HelloGreeting and assign as its value the string "Hello" plus the value of Name plus "how are you?". Note that this value is made up of three strings joined by two plus (+) signs. This is known as concatenation, which is a fancy term for the simple act of "stringing" strings together. In the third line, we ask Python to print HelloGreeting, which it does in the fourth line.

Indexing

As in Java and C, we can work with individual characters in a string. To access them we use indexing, in which the string characters, starting with the first one, are assigned consecutive numbers, or indexes. Thus, the first character is assigned the index 0; the second character, the index 1; and so forth. We can refer to these as "0 index" and "1 index." The numbers assigned to characters in a string are referred to as the string's indexes.

The following example should give you a clear picture of indexing.

>>> sample = "abcdefghijklmnopqrstuvwxyz" >>> sample 'abcdefghijklmnopqrstuvwxyz' >>> sample[1] 'b' >>> sample[0] 'a'

Here we first want the letter b, so we enter sample[1]. Next we want the letter a, so we enter sample[0]. Notice that the indexes are indicated by square brackets.

Just remember, novices, the index of the first character in a string is 0, not 1, which is why the index of z in the example above is 25, not 26.

Slice Notation

Another way to access parts of a string is with slice notation, which, simply put, allows you to enter a string (or a list or a tuple, which we'll get to shortly) and extract the "slice" you want to work with.

Let's look at an example:

>>> alphabet = "abcdefghijklmnopqrstuvwxyz" >>> AthruD = alphabet[0:4] >>> AthruD 'abcd'

The first line assigns the letters of the alphabet to the variable alphabet; the second line assigns the value of indexes 0 through 3 to the variable AthruD; the third line instructs Python to output AthruD; the fourth line is the result: 'abcd'.

Another way to write the slice [0:4] is as [:4]. An omitted first index tells Python to start at zero. In the same way, [1:] tells Python to start at index 1 and make the rest of the string the slice. The following example uses the slice notation in all three ways: without a first index in the first line; with both indexes in the fourth line; and without the second index in seventh line. Table 1-1 describes each of these slices in English.

>>> AthruD= alphabet[:4] >>> AthruD 'abcd'
Table 1-1. Slice Notation
Slice Meaning
AthruD=alphabet[:4] Assign the variable AthruD from the first character up to but not including the 4 index, i.e., index 0 through index 3.
EthruM=alphabet[4:13] Assign the variable EthruM from the 4 index up to but not including the 13 index.
NthruZ=alphabet[13:] Assign the variable NthruZ from the 13 index up to and including the last character in this string.
>>> EthruM = alphabet[4:13] >>> EthruM 'efghijklm' >>> NthruZ = alphabet[13:] >>> NthruZ 'nopqrstuvwxyz' >>> alphabet2 = AthruD + EthruM + NthruZ >>> alphabet2 'abcdefghijklmnopqrstuvwxyz' >>> alphabet 'abcdefghijklmnopqrstuvwxyz' 

The Slice

In a slice notation, the range of the slice is up to but not including the second index. Thus, a slice of [2:5] actually means the second through the fourth characters in a string.

Lists

A list is a built-in Python type (remember, we'll get to types in Chapter 2). It's in the same type family as a string and can contain either strings or numbers. Lists are somewhat like arrays in Java or C, except that they can contain values of different types.

The following example shows how a list uses slice notation:

>>> letters = "abcdefghijklmnop" >>> numbers = "123456789" >>> list = [letters, numbers, 1, 2, 3, 4, 5, 1.0, 2.0, 3.0, 4.0] >>> list[0] 'abcdefghijklmnop' >>> list[1] '123456789' >>> list[2] 1 >>> list[7] 1.0 >>> list[:] ['abcdefghijklmnop', '123456789', 1, 2, 3, 4, 5, 1.0, 2.0, 3.0, 4.0] >>> len(list) 11 >>> list = ["hello", "goodbye"] >>> list[0:2] ['hello', 'goodbye'] >>>len (list) 2

Python as a Main Program

In interactive mode, you work with Python one instruction at a time. When it's set up as a standalone program (i.e., not needing user interaction), Python performs any number of consecutive tasks. Just turn it on, and it does all the rest. To use Python this way, you first have to write a program and then save it as a text file.

Enter the following at your console and save it as campPython.py.

print "hello mother" print "hello father" print "greetings from camp Python"

Go to the command prompt and enter Jython campPython.py.

C:\book\chap1>jython campPython.py

The output is

hello mother hello father greetings from camp Python

Essentially, you've created a module called campPython.py, and the text you typed in is the module's main method the code that's executed first.

Now take a look at the next code example. It represents a module containing a class called Camp, a method called SayHello(), and a function called sayCampHello().

class Camp:       def sayHello(self):             return "\n Hello Mom \n Hello Dad" def sayCampHello():       camp = Camp()       print ("Hello: " + camp.sayHello()) if __name__ == "__main__":       sayCampHello()

If you're feeling adventurous, enter this module and run it, making sure to indent each line exactly as shown. Don't waste too much time trying to figure out what's going on, however. For that you have to know about functions, which are covered in Chapter 3, and classes, which are covered in Chapter 5 (along with methods). By the way, the line if __name__=="__main__": indicates that this part of the module should be executed if this script is run as the main program (from the command prompt example).

For Programmers Only

Novices, go ahead and read the following two subsections if you like, but they're way over your head right now.

Code Blocks

In the Camp example, notice that the class and function definitions don't have block delimiters but are delimited by whitespace only. In Python, indentation defines code blocks, so all Python programs look pretty much the same. This is in real contrast with other languages, such as C++ or Visual Basic, in which three different programmers can come up with three different styles for the same program. You should understand the issue if you've ever written a language style guide. In a Python style guide, defining the best style for delimiting code blocks is something you won't have to worry about.

Passing Arguments to a Program

If you're writing a utility application, you might want to be able to pass command-line arguments to the program. In Python, we do this by putting the arguments on the command line after the script.

C:\book\chap1>jython args.py hello how are you

Here we enter four command-line arguments in the args module. These arguments are stored in a list called argv in the sys module (sys must be imported before it can be used by args). The args.py module is an example of using the sys.argv variable.

import sys print(sys.argv[0]) print(sys.argv[1]) print(sys.argv[2]) print(sys.argv[3]) print(sys.argv[4])

The first line of args imports the sys module. The second through sixth lines place each command-line argument in the sys.argv list. This produces the following output:

args.py hello how are you

As you can see, sys.argv[0] equals args.py, which is the name of the script. argv[1:] equals the remaining command-line arguments hello, how, are, you. Remember, the slice notation argv[1:] indicates the 1 index through the end of the argv list.

Back to Basics

If you're working in a Python program, you can switch to interactive mode with the -i command-line argument, which allows the script to be interpreted and then inspected by the interactive interpreter. You'll be glad to have this feature if there's a bug in your code that you need to find and fix.

The following code is our campPython.py module, this time with the -i inserted before the module name in the first line.

C:\book\chap1>jython -i campHello2.py Hello:  Hello Mom  Hello Dad >>> camp = Camp() >>> print camp.sayHello()  Hello Mom  Hello Dad >>>

The Fast Track

Python supports control flow, functions, exception handling, object-oriented programming, and more, much like Java, Visual Basic, Perl, Delphi, and C++, among others. In syntax, Python is a lot like C, whose syntax is the basis of that used in Java, JavaScript, and C++.

Types

Python is a dynamically typed language, similar to Smalltalk. When you assign a variable a value, that value specifies the type. There are many built-in types in Python, but, unlike in Java, no primitive types. Functions, methods, classes, code blocks, namespaces, numbers, strings, and so forth, are all treated as objects that can be manipulated.

If you're a Smalltalk fan, you'll like Python. Of all of the mainstream programming languages, Python has the closest thing to Smalltalk's object model (it even has multiple inheritance).

Numeric Types

Numeric types are objects in Python. The built-in function type() indicates the type, as the following code snippet illustrates:

>>> myInt = 1 >>> type(myInt) <jclass org.python.core.PyInteger> >>> myFloat = 1.1 >>> type(myFloat) <jclass org.python.core.PyFloat> >>> myLong = 1l >>> type(myLong) <jclass org.python.core.PyLong>

You can add, subtract, divide, and multiply numeric types.

>>> num = 1 + 1 >>> print num 2 >>> average = (1+2+3)/3 >>> print average 2

Chapter 2 will tell you more about Python built-in types. Chapter 3 will tell you about Python-supported operators.

Collection Types

Python supports four main built-in collection types: strings, dictionaries, lists, and tuples. Strings, lists, and tuples are called sequences, for which Python provides many built-in operations. If you know Java, think of a list as a vector and a dictionary as a hashtable. If you know Visual Basic, think of a dictionary as a collection object or, if you know Perl, as an associative array. Like Perl and Visual Basic, Python has a built-in syntax for dealing with collections, which makes the code that works with them easier to write and understand. Java has no such syntax.

The example that follows shows how to declare an instance of each collection type.

>>> list = [1,2,3,4,5,6] >>> tuple = (1,2,3,4,5,6) >>> string = "123456" >>> dict = {"one":1, "two":2, "three":3, "four":4, "five":5, "six":6}

Here are the corresponding type names for each collection variable:

>>> type(list) <jclass org.python.core.PyList> >>> type (tuple) <jclass org.python.core.PyTuple> >>> type(string) <jclass org.python.core.PyString> >>> type(dict) <jclass org.python.core.PyDictionary>

Also like Perl and Visual Basic, Python allows effortless iteration through collections. Here's an example of iterating through each item in a list, and printing it to the console, using a for loop:

>>> for item in list: ...    print item ... 1 2 3 4 5 6

Here's the same for loop for a string and a tuple, respectively:

>>> for item in string: ...     print item ... 1 2 3 4 5 6 >>> for item in tuple: ...     print item ... 1 2 3 4 5 6

Note the indentation that marks the body of the for statement in all three examples. (Chapter 4 deals with for loops and for statements.)

All of the Python collection types can be indexed using the [ ] notation just like an array in Java or C. The following example shows how for lists, tuples, and strings:

>>> list[1] 2 >>> tuple[1] 2 >>> string[1] '2'

With dictionaries you use a key to index a value.

>>> dict["one"] 1

For any collection type, if you try to index a value that's not available (out of range, a nonexistent key, etc.), the collection object will throw an exception.

You can use the index to change the value held by a list or a dictionary at that index.

>>> list [0]=0 >>> print list [0, 2, 3, 4, 5, 6] >>> dict["one"]=0 >>> print dict {'one': 0, 'six': 6, 'two': 2, 'five': 5, 'three': 3, 'four': 4}

You can't do this with a string or tuple because these collection types are immutable.

Strings can be added and multiplied. Here's an example of addition:

>>> string2 = string + "789" >>> print string2 123456789

Here's an example of multiplication:

>>> string2 = string * 2 >>> print string2 123456123456 >>> print string 123456

Addition and multiplication also work for lists and tuples.

>>> list = list + [7, 8, 9] >>> list [0, 2, 3, 4, 5, 6, 7, 8, 9] >>> tuple = tuple + (7,8,9) >>> tuple (1, 2, 3, 4, 5, 6, 7, 8, 9)

There are many built-in operations for dealing with collections. One example finds the minimum and maximum item; another determines the collection length. See Chapter 2 for more on built-in types and Chapter 9 for more on built-in functions and operations.

Control Flow

Python provides all of the control flow constructs (discussed in Chapter 4) that an experienced programmer is used to: if, while, and for. The only difference between these constructs in Python and their counterparts in other languages is their use of indentation to define code blocks.

Here's a simple if statement. Note that, unlike Java, Python uses numerics as Boolean values; thus, any nonzero value is considered true.

>>> var1=1 >>> if var1: ...     print "hello" ... hello

Here's a more complex if statement that uses elif ("else if") and else blocks:

>>> var1 = 1 >>> if var1==1: ...     print "Hello" ... elif var1==2: ...     print "Goodbye" ... else: ...     print "Later on" ... Hello

You see that, if the first test passes (var1 == 1:), the second (var1 == 2:) doesn't execute, even though both may be true.

while statements work as expected. The back quotes get a string representation of var1.

>>> while var1 > 10: ...     print "var1 = " + 'var1' ...     var1 = var1 - 10 ... var1 = 100 var1 = 90 var1 = 80 var1 = 70 var1 = 60 var1 = 50 var1 = 40 var1 = 30 var1 = 20

Earlier we used a for loop to iterate through a collection. The use of for in a more traditional fashion requires the xrange() built-in function. The following Python example is equivalent to the one that follows it, which uses a basic C-like syntax.

>>> for index in xrange(0, 100, 10): ...     print `index` ...       for(int index = 0; index < 100; index += 10){             System.out.println(index)       }

If you leave out the 10 in the call to xrange(), it defaults to incrementing by 1. Thus, the following example iterates 100 times (0 100).

>>> for index in xrange(0, 100):

Chapter 3 deals with comparison operators; Chapter 4, with control flow.

Exception Handling

Like so much of Python, exception handling is a lot like its counterparts in other languages. For example, Python's try clause is like Java's try, and its except clause is like Java's catch. Consider an exception thrown by a dictionary object if we try a nonexistent key. In this case, the interpreter simply prints the exception out to the screen.

>>> dict = {"Green Eggs":"Ham"} >>> dict["Blue Eggs"] Traceback (innermost last):   File "<console>", line 1, in ? KeyError: Blue Eggs

To handle this exception we can do this:

>>> try: ...     dict["Blue Eggs"] ... except KeyError, error: ...     print "Sam, Blue Eggs do not go with Ham " + 'error' ... Sam, Blue Eggs do not go with Ham <exceptions.KeyError instance at -864407725>

KeyError refers to the class of the exception that we want to catch, and error refers to the instance of KeyError. Here's the equivalent Java pseudocode:

try{             dict.index("Blue Eggs"); } catch(KeyError error){       System.out.println("Sam, Blue Eggs do not go with Ham"                         + error); }

C++'s pseudocode is similar.

In addition to try...except, Python has a try...finally block. Its finally clause works much like Java's finally block, but it can't be mixed with except, as Java's can be mixed with its catch. Instead, you have to nest Python's try...catch blocks inside its try...finally blocks.

Chapter 7 deals with Python exception handling.

Functions

As usual, Python's functions are similar to other languages' functions. That is, they perform one action and return a value. However, unlike Visual Basic and Pascal, Python uses the same syntax to define both functions and procedures, which perform multiple actions.

Here's a function that sums two numbers and returns their value:

>>> def sum(num1, num2): ...     return num1 + num2 ... >>> sum(5,5) 10

It shows how Python, like Visual Basic, uses named arguments and default values, which allow customization of function calls.

>>> def sum(var1=0, var2=0, var3=0): ...     return var1 + var2 + var3 ... >>> sum() 0 >>> sum(1,1) 2 >>> sum(var1=5, var3=5) 10

Because Python is dynamically typed, the sum function works with numeric types as well as strings.

>>> sum("Hello, ", "Mom, ", "how are you?") 'Hello, Mom, how are you?'

A function that doesn't return a type automatically returns the value None. Python's None is like Java's null, Visual Basic's Nothing, and Delphi's Nil. It means nothing or no value, not the integer value zero.

Chapter 5 covers functions in detail.

Modules and Packages

If you're from a Java or C++ background, a Python module will seem like a cross between a package and a class with static methods. Modules can contain classes, functions, and data objects. Essentially they're files that contain Python definitions classes and functions and Python statements; they can be imported into other modules or into the main module. Module file names are appended with the suffix .py.

Python modules are similar to *.java files and look and act very much like Visual Basic modules. See Chapter 5 to learn more about them. This chapter also discusses Python packages, which help group and organize a set of related modules.

Classes and OOP

Like their counterparts in other languages, classes in Python are collections of variables and the methods that operate on them. To illustrate, here's an example class, Car, that inherits from the two other classes, Automobile and Transportation:

>>> class Automobile: ...     pass ... >>> class Transportation: ...     pass ... >>> class Car(Automobile, Transportation): ...     make="Ford" ...     model="Taurus" ...     def __init__(self, make, model): ...             self.make=make ...             self.model=model ...     def __del__(self): ...             print "similar to a destructor" ...     def __str__(self): ...             str = "Make " + self.make ...             str = str + ", Model " + self.model ...             return str ...

We can create an instance of Car and call it car.

>>> car = Car("Chevy", "Nova") #Create an instance of car >>> print car Make Chevy, Model Nova

And we can show that car is also an instance of classes Car and Automobile.

>>> print isinstance(car, Car) 1 >>> print isinstance(car, Automobile) 1

Note that Car defines two methods: __init__, which acts as a constructor; and __del__, which acts as a destructor. __str__ returns a string representation of the class.

Unlike Java classes, Python classes can have multiple inheritance, which we saw above with Car inheriting functionality from both Automobile and Transportation. In this regard, Python is more like C++ and Smalltalk.

Chapters 5 and 6 cover Python classes. Chapter 9 covers built-in operations and functions that pertain to classes.

Working with Java from Python

The following interactive session shows how to import and use Java classes from Python:

Import the Frame class from the java.awt package.

>>> from java.awt import Frame

Create an instance of Frame, named frame.

>>> frame = Frame("My first frame created in Jython")

Call frame's setVisible() method

>>> frame.setVisible(1)

Import the Button class from java.awt.

>>>from java.awt import Button

Create an instance of Button, called hit_me.

>>>hit_me = Button ("Hit me!")

Create a handler for Button (the event handler is just a function).

>>>def hit_me_event_handler(event): ...     print "Ouch!" ...

Register the handler with the function.

>>>hit_me.actionPerformed = hit_me_event_handler

Add button to frame by calling frame's add() method.

>>> frame.add(hit_me) java.awt.Button[button0,0,0,0x0,invalid,label=Hit me!]

Call frame's pack() method so that the button will be visible.

>>>frame.pack()

Click the button with the mouse and watch the output in the interactive interpreter.

Chapter 11 covers working with Java APIs from Python.

The Power of Python

Python can make tough tasks trivial. Let's prove this by an example. How many lines of code will it take you in your favorite language to parse the following string and put each value in a variable?

>>> str = "Rick Hightower, 555-1212,rick_m_hightower@emailcompany.com 

Can you parse it in ten lines? Maybe five? Python can do it in one (not including the import statement).

>>>from string import split >>>name, phone, email = split(str, ",") 

This is what we get:

>>> print name Rick Hightower >>> print phone  555-1212 >>> print email  rick_m_hightower@emailcompany.com >>> 

Simple parsing using the split() function is covered in Chapter 10; more advanced parsing using regular expressions is covered in Appendix E.

Here's an easy way to print the variables name, phone number, and email from the above session. It shows how, in Python, every namespace equates to a dictionary.

>>> v = "%(name)s's phone number and email is %(phone)s and %(email)s" % locals() #one line >>> print v Rick Hightower's phone number and email is 555-1212 and rick_m_hightower@emailcompany.com 

Chapter 3 covers Python string formatting. It's a lot like string formatting in C, with its sprintf() and printf() functions, so you should pick it up quickly if you have any C background.

Where Do You Go from Here?

If you're an experienced C++ programmer you can skip to Chapter 8, although you might want to skim Chapters 2 through 7 and use them as a reference. Visual Basic programmers can skip to Chapter 8 as well, with detours to Chapter 6 (on object-oriented programming) and 7 (on exception handling) and a skim of Chapters 2 though 5.

Novice Java programmers with no C experience should concentrate on the last half of Chapter 3 (on string formatting) and the last half of Chapter 6 (on dynamic polymorphism and operator overloading) and skim Chapters 2 through 5. If you're comfortable with Java, see Appendix C,which creates equivalent Java and Python programs for comparison.

Summary

This chapter introduced some basic programming concepts. Having downloaded and installed the Java Development Kit (JDK), Jython, and the Jython libraries, and having dipped your toe in the Python interactive interpreter, you should have a pretty good feel for what programming is. Don't worry if you still feel confused. Your confusion will go away after the next few chapters. Once you've read up through Chapter 8, you'll feel confident using Python you'll feel like a programmer. After that, we'll get into the really fun stuff: graphical user interfaces and applets.

If you want to learn more about Python on your own, go to www.python.org, www.sourceforge.net and www.jython.org, or go to www.sourceforge.net and look for Jython. (That's not a typo. JPython now goes by the name Jython.) At any of these sites, you can sign up for the email list, view the documentation, visit some of the contributor sites, and join a newsgroup.

CONTENTS


Python Programming with the JavaT Class Libraries. A Tutorial for Building Web and Enterprise Applications with Jython
Python Programming with the Javaв„ў Class Libraries: A Tutorial for Building Web and Enterprise Applications with Jython
ISBN: 0201616165
EAN: 2147483647
Year: 2001
Pages: 25

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net