Sie sind auf Seite 1von 557

Python Programming with the Java Class Libraries: A Tutorial for Building

Web and Enterprise Applications with Jython


By Richard Hightower
Publisher: Addison Wesley
Pub Date: June 28, 2002

Table of
Contents

ISBN: 0-201-61616-5
Pages: 640

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
Object-oriented programming concepts
File input/output
Python's intrinsic functions
Formatting, parsing, and manipulating strings
Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs
Working with SQL and JDBC(TM)
Python and Java applets
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Copyright

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
A Very ShortByHistory
Richard Hightower

Preface

What You Will Learn


The Audience Publisher: Addison Wesley
Acknowledgments
Pub Date: June 28, 2002

ISBN: 0-201-61616-5
Table of
Chapter 1. Jython Overview
Pages: 640
Contents
Programming, Briefly
Learning Python
First
Characterized
by ease

of use, richness of expression, and concise syntax, Python has


programming language for more than a decade, and is used by
novices
Starting with
Pythonand professionals alike. In particular, its close relationship to Java(TM) makes
the
when used in combination, ideal for Web and distributed enterprise
Basic Functionstwo
withlanguages,
Python
application
development.
Python as a Main Program
remained a premier
Python the Language

The Fast Track

This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
Where Do You Go from Here?
help those new to programming develop an understanding of concepts and practical
Summary
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
Chapter 2. Statements and Expressions
application development.
The Power of Python

Comments and Document Strings


Statements Python
Expressionsand

Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
Enterprise Applications with Jython covers important topics such as:

Variables
Data Types

Fundamental programming concepts, including statements, expressions,


interpreters, and compilers

Python Collection Types

Advanced Topic: Determining Types at Runtime


Literals

Python basics, including operators, string formatting, namespaces, classes, errors,


and exceptions

Summary

Chapter 3. Operators
and String Formatting
Object-oriented
programming concepts
Operators

File input/output
Formatting StringsModulus
Summary

Python's intrinsic functions

Chapter 4. Control Flow


The if Statement

Formatting, parsing, and manipulating strings

The while Statement


Interfacing

with the Java APIs and working with Java Streams

The for Statement

Using
Putting It All Together
Summary

Python and Java Swing to create GUIs

Working with SQL and JDBC(TM)

Chapter 5. Organizing Your Code

Python and Java applets

Evolution of a Programmer

Code BlocksIn
and
Namespaces
addition,
the book contains

instructions for downloading and installing the Python


language and the Java Development Kit (JDK). Terminology, definitions, explanations,
Functions and
andMethods
numerous code samples make this book a useful learning experience.
Modules

Putting Things Together

Whether you are a sophisticated computer user new to programming or a serious


Packages application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.
Globals and the Global Statement
Classes

Summary

777

Chapter 6. Object-Oriented Programming

What Is OOP?
Python Programming with the Java Class Libraries: A Tutorial for Building
Objects andWeb
Classes
and Enterprise Applications with Jython
Special Class
ByMethods
Richard Hightower
Inheritance
Polymorphism Publisher: Addison Wesley
Summary

Pub Date: June 28, 2002

ISBN: 0-201-61616-5
Table of
Exceptions
Chapter 7. Errors and
Pages:
640
Contents
Syntax and Sequence Errors
The Danger Characterized
of Exceptions by ease

of use, richness of expression, and concise syntax, Python has


a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
The raise Statement
two languages,
when used in combination, ideal for Web and distributed enterprise
Classes andthe
Instances
as Exceptions
application
development.
Getting the Most Out of Your Exceptions
remained
The try Statement

Summary

This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
Chapter 8. Working with Files
help those new to programming develop an understanding of concepts and practical
Simple File Operations
techniques. For experienced programmers, the book demonstrates Python's breadth of
Common File Methods
capabilities and shows the ways that Python interfaces with Java APIs for professional
Putting It All Together: The Address Book Example
application development.
The Full address3.py Code

Persisting Objects
pickle
Pythonwith
Programming

with the Java(TM) Class Libraries: A Tutorial for Building Web


Jython covers important topics such as:

pickle and the


BookApplications
Application with
andAddress
Enterprise
Summary

Fundamental programming
Chapter 9. Built-In Functions

concepts, including statements, expressions,

interpreters, and compilers

Conversion

Namespace: dir(), globals(), locals(), vars()

Python basics, including operators, string formatting, namespaces, classes, errors,


and exceptions

Type Checking: callable(), type()


Operations

Advanced Topic: Functional


Programming
Object-oriented
programming concepts
Advanced exec and eval

File input/output

Summary

Python's intrinsic functions

Chapter 10. Working with Strings

Conversion: atoi(), atof(), atol()

Formatting, parsing, and manipulating strings

Case Change: capitalize(), capwords(), swapcases(), lower(), upper()


Finding: find(), rfind(),
index(),
rindex(),
replace()
Interfacing
with
the Javacount(),
APIs and
working with Java

Streams

Splitting and Joining: split(), splitfields(), join(), joinfields()

Usinglstrip(),
Pythonrstrip(),
and Javastrip()
Swing
Stripping and Parsing:

to create GUIs

Adjusting Text: ljust(), rjust(), center(), zfill(), expandtabs()

Working with SQL and JDBC(TM)

Summary

Python and Java applets

Chapter 11. Interfacing with Java


Using the Java
APIs
In addition,

the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
Constructors
and numerous code samples make this book a useful learning experience.

Java Types
Java

Java Arrays and jarray

you are
Java Arrays Whether
and Methods

a sophisticated computer user new to programming or a serious


application
developer,
Python Programming with the Java(TM) Class Libraries will
Bean Properties
give
you
insight
into
the
power of Python and the know-how to put it to work.
Properties
Java Event Handling

777

Subclassing Java Classes


Advanced Topics

Summary

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
Chapter 12. Working
with
Java Streams
By Richard
Hightower
The Java Way of File Operations
Text Streams Publisher: Addison Wesley
Binary Streams:
InputStream
Pub
Date: June and
28, OutputStream
2002
DataInput and DataOutput
ISBN: 0-201-61616-5
Table of
The File Class

Pages: 640
Contents
The RandomAccessFile Class
The StreamTokenizer
Classby ease
Characterized

of use, richness of expression, and concise syntax, Python has


language for more than a decade, and is used by
novices
and
professionals
alike.
In
particular, its close relationship to Java(TM) makes
Using Java Streams to Work with Memory
the
two
languages,
when
used
in
combination,
ideal for Web and distributed enterprise
Summary
application development.
remained
a premier
programming
Persisting Objects
with
Java Streams

Chapter 13. JFC Fundamentals

This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
JFrame
help those new to programming develop an understanding of concepts and practical
Handling Events with JFrame
techniques. For experienced programmers, the book demonstrates Python's breadth of
The Python Way of Handling Events
capabilities and shows the ways that Python interfaces with Java APIs for professional
The Class Hierarchy for JFrame and Frame
application development.
Components and Containers

JPanel
JLabel

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
Enterprise Applications with Jython covers important topics such as:

JComponentand
JButton
JTextField
JCheckBox
JRadioButton
List and JList
Summary

Fundamental programming concepts, including statements, expressions,


interpreters, and compilers
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions

Chapter 14. First Swing


Application, programming
Layout, and Menus
Object-oriented
concepts
Putting Things Together with Basic Java GUIs

File for
input/output
Adding an Input Form
an Address Entry: The Prototype
Adding an Input Form for an Address Entry: First Cut

Python's intrinsic functions

Adding a Main Window for the Address Book Application: Prototype


Adding a Main Window:
First Cut
Formatting,
parsing, and manipulating strings
Adding a Toolbar and a Dialog for the Address Book Application

Interfacing with the Java APIs and working with Java Streams

Menus
Layout Managers

Using Python and Java Swing to create GUIs

A GridBagLayout Example

Putting Things Together: Adding GridBagLayout to the Address Application


Summary

Working with SQL and JDBC(TM)


Python and Java applets

Chapter 15. Graphics and Events


A Quick Graphics
Tour
In addition,

the book contains instructions for downloading and installing the Python
Development Kit (JDK). Terminology, definitions, explanations,
andTogether:
numerousAcode
samples
make this book a useful learning experience.
Putting Things
Drawing
Program
language
and Events
the Java
A Quick Tour
of Common

The Complete Shapes and DrawShapes Modules


Summary
Chapter 16.

Whether you are a sophisticated computer user new to programming or a serious


application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.
Advanced Swing

JTable

777

Working with Table Models


Putting Things TogetherAdding a Table Model to the Address Book Application

JTree

Python Programming with the Java Class Libraries: A Tutorial for Building
JToolBar and
Actions
Web
and Enterprise Applications with Jython
Summary By Richard Hightower
Chapter 17. SQL Publisher:
and JDBC Addison Wesley
A Quick and Dirty
PubJDBC
Date:Session
June 28, 2002
Programming with ISBN:
JDBC and
SQL
0-201-61616-5
Table of
SQL Data Definition
Language

Pages:
640
Contents
SQL Data Manipulation Language
Putting It AllCharacterized
TogetherAdding
Database
Support of
to expression,
the Addressand
Book
Application
by ease
of use, richness
concise
syntax,

Python has
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
Chapter 18. Applets
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
What Are Applets?
Summary

Working with Applets

This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
Transforming the Address Book Application into an Applet
help those new to programming develop an understanding of concepts and practical
Advanced Topic: AppletContext and AppletStub
techniques. For experienced programmers, the book demonstrates Python's breadth of
Summary
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
Using an Applet as a Container

Appendix A. Installing Jython on Windows


Installing Java
Runtime
Python
Programming

with the Java(TM) Class Libraries: A Tutorial for Building Web


with Jython covers important topics such as:

Installing the
J2SEStep
Step
and
EnterprisebyApplications
Installing Jython

Fundamental
programming
Appendix B. Installing
Jython on Linux

concepts, including statements, expressions,

interpreters,
and compilers
Unpacking the Blackdown
Package
Unpacking the Sun Package

Python basics, including operators, string formatting, namespaces, classes, errors,


and exceptions

Installing the Sun and Blackdown Distributions


Installing Older Distributions
Running Jython

Object-oriented programming concepts

Appendix C. The Power


Scripting
Fileofinput/output
Scripting Versus Programming Languages
Java and ScriptingPython's intrinsic

functions

Integrating Scripting with Jython

Formatting, parsing, and manipulating strings

Which Scripting Language to Choose

Hello WorldThe Programming


Rosetta
Stone
Interfacing with
the Java
APIs

and working with Java Streams

What Does It All Mean?

Using Python and Java Swing to create GUIs


Appendix D. Java and Python: A Comparison

Working with SQL and JDBC(TM)

Python 101
A GUI Application

Python and Java applets

A Statistics Application

A String Parsing Example

In addition, the book contains instructions for downloading and installing the Python
Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.

Embedding language
Jython in and
Javathe

Appendix E. Regular Expressions


A Simple Example
Whether

you are a sophisticated computer user new to programming or a serious


developer, Python Programming with the Java(TM) Class Libraries will
Regular Expression
andthe
Error
andofFlags
Properties
give youFunctions
insight into
power
Python
and the know-how to put it to work.
Pattern Characteristics
application

re Object Methods and Properties


Match Object Methods and Properties

777

Metacharacters

Putting Things Together

Copyright

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

Many of the designations used by manufacturers and sellers to distinguish their products are claimed as
Publisher: Addison Wesley
trademarks. Where those designations appear in this book, and Addison-Wesley was aware of a trademark
Pub Date: June 28, 2002
claim, the designations have been printed with initial capital letters or in all capitals.
ISBN: 0-201-61616-5
Table of
Pages:
640
author
and publisher have taken
care in the preparation of
Contents

The
this book, but make no expressed or implied
warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for incidental
Characterized
by ease
of use,
richness
andinformation
concise syntax,
Python has
or consequential damages
in connection
with
or arising
outofofexpression,
the use of the
or programs
contained
remained
a
premier
programming
language
for
more
than
a
decade,
and
is
used by
herein.
novices and professionals alike. In particular, its close relationship to Java(TM) makes
two languages,
whenwhen
usedordered
in combination,
ideal
and distributed
enterprise
The publisher offers the
discounts
on this book
in quantity
for for
bulkWeb
purchases
and special
sales. For
application
development.
more information, please contact:

This tutorial Sales


begins with coverage of some of the basics of Python programming. Using
U.S. Corporate and Government
plenty of skill-building exercises and interactive programming sessions, this book will
(800) 382-3419
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
corpsales@pearsontechgroup.com
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
For sales outside of the U.S., please contact:
International Sales

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

(317) 581-3793

Fundamental programming concepts, including statements, expressions,


international@pearsontechgroup.com
interpreters, and compilers
Visit Addison-Wesley on the Web: www.awprofessional.com
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
Library of Congress Cataloging-in-Publication
Data
Hightower, Richard.

Object-oriented programming concepts

input/output
Python programming with File
the Java
class libraries : a tutorial for building Web and Enterprise applications with
Jython / Richard Hightower.
Python's intrinsic functions
p. cm.

Formatting, parsing, and manipulating strings

ISBN 0-201-61616-5 (alk. paper)


Interfacing with the Java APIs and working with Java Streams
1. Python (Computer program language) 2. Java (Computer program language) 3. Application
Using Python and Java Swing to create GUIs
softwareDevelopment. I. Title.
QA76.73.P98 H54 2002

Working with SQL and JDBC(TM)


Python and Java applets

005.2'762dc21

In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
numerous
code samples
Copyright 2003 byand
Pearson
Education,
Inc. make this book a useful learning experience.
2002066565

Whether
a sophisticated
userstored
new toinprogramming
or a serious
All rights reserved. No
part ofyou
thisare
publication
may becomputer
reproduced,
a retrieval system,
or transmitted, in
application
developer,
Python
Programming
with
the
Java(TM)
Class
will
any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise, Libraries
without the
prior
give
you
insight
into
the
power
of
Python
and
the
know-how
to
put
it
to
work.
consent of the publisher. Printed in the United States of America. Published simultaneously in Canada.
For information on obtaining permission for use of material from this work, please submit a written request to:

777

Pearson Education, Inc.

Programming
Rights and ContractsPython
Department

with the Java Class Libraries: A Tutorial for Building


Web and Enterprise Applications with Jython
Richard
75 Arlington Street, By
Suite
300 Hightower

Boston, MA 02116

Publisher: Addison Wesley

Fax: (617) 848-7047

Text

Pub Date: June 28, 2002

Table of
printed
on recycled
Contents

ISBN: 0-201-61616-5
Pages: 640

paper

Characterized by ease of use, richness of expression, and concise syntax, Python has
1 2 3 4 5 6 7 8 9 10CRS0605040302
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
First printing, July 2002
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.

Preface

This tutorial begins with coverage of some of the basics of Python programming. Using
of skill-building
and interactive
programming
sessions,
book
willand
Python is a dynamic plenty
programming
languageexercises
with the power
of well-known
languages
such asthis
Java,
C++,
help those
newand
to programming
develop
an understanding
and practical
Smalltalk. In fact, Python
is leaner
meaner than any
of these
languages andof
yetconcepts
very expressive;
it doesn't
talk much, but it hastechniques.
a lot to say.For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
Python has another plus:
the simplicity
of languages such as VB Script and JavaScript, which makes it easy for
application
development.
beginning programmers to learn. Novices who know their way around a computer can pick it up quickly,
Python
with the that
Java(TM)
Libraries:data,
A Tutorial
Building Web
particularly if they have
everProgramming
created a spreadsheet
graphsClass
and organizes
writtenfor
spreadsheet
formulas,
andFor
Enterprise
Applications
Jython
covers
such as: in any language,
or created a Web page.
those who
have, say, with
written
macros
and important
batch filestopics
or programmed
Python will be a breeze.
Fundamental programming concepts, including statements, expressions,

A Very Short History


interpreters, and compilers

basics,
including
operators,
stringvan
formatting,
Python was derived from aPython
language
called
ABC created
by Guido
Rossum namespaces,
and others in classes,
the earlyerrors,
1980s.
and
exceptions
The hope was that ABC's designed-in ease of use would become popular with novices as a way to get up to
programming speed quickly and painlessly. This hope didn't pan out, so van Rossum began a new project,
Object-oriented programming concepts
Python, which was released in 1990. He didn't forget ABC; in fact, there's a lot of ABC in Python's concise
syntax and elegant expression,
well as in its ease of use. The formula worked this time; Python succeeded
File as
input/output
where ABC failed, and it has stood the test of time.
Python's intrinsic functions

What You Will Learn


Formatting, parsing, and manipulating strings
Put simply, my goal with this
book is towith
teach
Python.
learn the workings of Python
Interfacing
theprogramming
Java APIs andusing
working
withYou'll
Java Streams
and how to apply them, particularly for the following:
Using Python and Java Swing to create GUIs
Abstract Windows Toolkit
(AWT)
and Swing
application development
Working
with SQL
and JDBC(TM)
Java applet development
Python and Java applets
Internet programming
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
Regular expressions
and pattern
and numerous
codematching
samples make this book a useful learning experience.
You may not understand
theseyou
concepts
now, but youcomputer
will by the
endnew
of the
book.
Whether
are a sophisticated
user
to programming
or a serious

application developer, Python Programming with the Java(TM) Class Libraries will
If you're looking for a full language reference, you won't get it here. What you will get is a deep enough
give you insight into the power of Python and the know-how to put it to work.
understanding of Python to get started on your own programming. I'm going to remind you often of my belief
that the best way to learn programming is by doing it. That's why I've provided lots of hands-on exercises in the
form of interactive programming sessions, which I hope you'll follow along with at the keyboard as you read.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
The Audience
Web and Enterprise Applications with Jython
By Richard Hightower

As a reader of this book, you may be one of the following:


Publisher: Addison Wesley

Pub
Date:
June
A nonprogrammer
who
wants
to 28,
learn2002
a programming language

ISBN: 0-201-61616-5
Table
of programmer who wants to learn Python
A novice
Pages: 640
Contents

For simplicity, I'll call


you both novices.
You
knowrichness
your computer
and how
use it tosyntax,
get thePython
job done.
Characterized
by ease
of use,
of expression,
andtoconcise
has

remained a premier programming language for more than a decade, and is used by
If you're not a novice and you're reading this book, then you're an experienced programmer who wants to learn a
novices and professionals alike. In particular, its close relationship to Java(TM) makes
higher-level language that's quicker and more powerful than the one you're using now. For simplicity, I'll call you
the two languages, when used in combination, ideal for Web and distributed enterprise
programmers.
application development.

For Novices This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
those new
to programming
develop
understanding
of examples.
concepts and
practical
You'll be introducedhelp
to Python
in conversational
English,
withanmany
step-by-step
Chapters
2 through
techniques.
For
experienced
programmers,
the
book
demonstrates
Python's
breadth
of
9 build progressively on the chapters preceding them, so you should be able to learn enough to begin writing
capabilities
and
shows
the
ways
that
Python
interfaces
with
Java
APIs
for
professional
useful Python programs. The goal is to give you as much of a headstart as possible. From Chapter 10 on you'll
application
development.
learn more about Python
and about
supporting Java and Python libraries on your own, as well as about Internet
programming with Python.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

For Programmers

Most likely you're an experienced


Java programmer
who's
awareincluding
of the close
relationship
between Java and
Fundamental
programming
concepts,
statements,
expressions,
Python and how it can leadinterpreters,
to better application
development (we'll get into this more in Chapter 1). You can
and compilers
skip over or skim the basic material and concentrate on the Advanced Topic sections and the various sidebars
basics, including operators, string formatting, namespaces, classes, errors,
that are geared to your levelPython
of understanding.
and exceptions
Now let's get into our tour of Pythonthe destination is worth the trip.
Object-oriented programming concepts

Acknowledgments
File input/output
Python's
intrinsic
The author and publisher are
grateful
for the functions
efforts of this book's developmental editor, Dianne Cannon Wood,
and reviewer, Barry Busler. Countless hours and suggestions were extremely helpful during the book's
production stages. Thanks.Formatting, parsing, and manipulating strings
Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs
Working with SQL and JDBC(TM)
Python and Java applets
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
CONTENTS
Web and Enterprise Applications with Jython
By Richard Hightower

Chapter 1. Jython
Overview
Publisher: Addison Wesley
Pub Date: June 28, 2002

Programming, Briefly
ISBN: 0-201-61616-5
Table of
Learning Python Pages:
First 640
Contents
Python the Language
Characterized
Starting with
Python by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
Basic Functions with Python
novices and professionals alike. In particular, its close relationship to Java(TM) makes
Python as athe
Main
two Program
languages, when used in combination, ideal for Web and distributed enterprise
The Fast Track
application development.
The Power of Python
This tutorial
begins
with coverage of some of the basics of Python programming. Using
Where Do You
Go from
Here?
plenty of skill-building exercises and interactive programming sessions, this book will
Summary

help those new to programming develop an understanding of concepts and practical


techniques. For experienced programmers, the book demonstrates Python's breadth of
Terms in This Chapter
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
Applet
Main method
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and
Enterprise
important topics such as:
Boolean
value Applications with Jython covers
Method
Bytecode
Module
Fundamental programming concepts, including statements, expressions,
Class interpreters, and compilers
Object

Python basics, including operators, string


formatting, namespaces, classes, errors,
Compiler
Programming
and exceptions
Concatenation
Pseudocode
Object-oriented programming concepts
Control flow
Script
File input/output
Expression
Sequence
Python's intrinsic functions
Floating-point number
Servlet
Formatting, parsing, and manipulating strings
for loop
Slice notation
Interfacing with the Java APIs and working with Java Streams
Function
Statem ent
Using Python and Java Swing to create GUIs
Immutability
String
Working with SQL and JDBC(TM)
Index/Indexing
Syntax
Python and Java applets
Interactive mode
Type
In addition, the book contains instructions for downloading and installing the Python
Interpreter
ValueTerminology, definitions, explanations,
language
and the Java Development Kit (JDK).
and numerous code samples make this book a useful learning experience.
Iteration
Variable
Whether you are a sophisticated computer user new to programming or a serious
Macro
application
developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.
In this chapter you will learn just what Python programming is and how to save and run Python scripts.

777

Programming, Briefly

You may have programmed


computer without
it. ForLibraries:
example, A
have
you ever
or
Python aProgramming
witheven
theknowing
Java Class
Tutorial
forwritten
Building
recorded a spreadsheet
macro
any otherApplications
macro for anywith
type Jython
of application)? If you have, you've programmed.
Web
and (or
Enterprise
Of course, programming
is a lotHightower
more complicated than writing macros; still, many people are overly
By Richard
apprehensive when it comes to learning this skill.
Publisher: Addison Wesley

You're going to find outPub


thatDate:
there'sJune
often
not much difference between a macro or a scripting language and
28, 2002
"real" programming. However, macro and script don't intimidate novice users, whereas programming does. The
ISBN: 0-201-61616-5
Table
point
is
that of
learning programming doesn't have to be hard. In fact, the hardest part about it is having the right

Pages: 640
Contents
attitude.
If you believe you can't learn to program, you probably won't.

Characterized
by is
ease
of use, richness
of expression,
and concise
syntax, Python
At its most basic level,
programming
instructing
the computer,
in a language
that it understands,
sohas
that it can
remained
a
premier
programming
language
for
more
than
a
decade,
and
is
used
by
perform tasks. Like any language you learned in high school, a programming language has a vocabulary,
novices andand
professionals
alike.The
In particular,
its close
relationship
to Java(TM)
makes
grammar, syntax, punctuation,
parts of speech.
trick is knowing
how
to use these
components
correctly
the
two
languages,
when
used
in
combination,
ideal
for
Web
and
distributed
enterprise
so that you get your point across and the job gets done.
application development.
Consider this very simple instruction:
This tutorial begins with coverage of some of the basics of Python programming. Using
of skill-building exercises and interactive programming sessions, this book will
write("Hello plenty
World")
help those new to programming develop an understanding of concepts and practical
Called a statement, it's
the primary
blockprogrammers,
of programming.
It "invokes,"
or "calls,"
the write
techniques.
Forbuilding
experienced
the book
demonstrates
Python's
breadth function.
of
capabilities and shows the ways that Python interfaces with Java APIs for professional
A function is a grouped
set of statements.
Within a program, one function can perform a task in its entirety, but
application
development.
more likely it will call another function, which in turn can call other functions, and so on, all of which together
Python
Programming
withbeing
the Java(TM)
Class Libraries:
A Tutorial
Building
Web
organize the program's
statements.
Remember
told in English
class to organize
yourfor
thoughts
into
a
and
Enterprise
Applications
with statements
Jython covers
such as: languages.
cohesive whole to get
your
point across?
This is what
andimportant
functionstopics
do in computer
Languages like Python need an interpreter to translate a human-generated program into a "machine-readable"
programming
concepts,
statements,
expressions,
form that the computer canFundamental
understand. Other
languages,
such asincluding
C and C++,
use a compiler.
The difference
andthe
compilers
between the two is that theinterpreters,
compiler saves
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
basics,
operators,
formatting,
namespaces,
classes,
program running when thePython
translation
wasincluding
made. The
upshot isstring
that compiled
programs
are faster
thanerrors,
and
exceptions
interpreted programs.

Object-oriented programming concepts

Learning Python First

File input/output

Learning any one programming


language
makes
it much easier to understand not only computers but other
Python's
intrinsic
functions
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 Formatting,
get under your
belt asand
a first
step on thestrings
way to Visual Basic, Java, and so forth.
parsing,
manipulating
It's important to understandInterfacing
that not allwith
languages
areAPIs
alike.
Forworking
example,
some,
as C++, Java, and Python,
the Java
and
with
Javasuch
Streams
areterse. 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. Toand
illustrate,
let's pretend
Using Python
Java Swing
to createwe're
GUIsasking 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:Working with SQL and JDBC(TM)
Walk to your garage.Python and Java applets
Open the garage door.
In addition,
Walk to the driver's
side ofthe
thebook
car. contains instructions for downloading and installing the Python
language
and
the
Java Development Kit (JDK). Terminology, definitions, explanations,
Put the key in the door.
and
numerous
code
samples make this book a useful learning experience.
Unlock the door.
Sit in the driver's seat
Whether you are a sophisticated computer user new to programming or a serious
You get the picture. application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.
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.
1.
2.
3.
4.
5.
6.

777

A higher-level language
abstracts
(i.e., hides)with
the complexity
a lower-level
language.
It looks
at the bigger
Python
Programming
the Javaof
Class
Libraries:
A Tutorial
for Building
picture and omits theWeb
details,
we saw in how
Python and
Assembly
andasEnterprise
Applications
with
Jythontell us how to get to Phoenix. The tradeoff
is that a lower-level By
language
friendlier to the computerit can run fasterwhereas a higher-level language is
RichardisHightower
friendlier to the programmershe can program faster. There's a hierarchy of complexity with programming
languages: C and C++ are
higher level
thanWesley
Assembly; Java is higher level than C++; and Python is higher level
Publisher:
Addison
than Java. The higher the
level,
the
greater
the
ease of use. The goal is making a language easy to use without
Pub Date: June 28, 2002
draining its power.
ISBN: 0-201-61616-5

Table of
Contents

Pages: 640

Python the Language

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
Python is a dynamic object-oriented language (i.e., flexible) for writing applications, Java applets and servlets,
novices and professionals alike. In particular, its close relationship to Java(TM) makes
and the like. (We'll learn more about applets in Chapter 18.) It has a close relationship with Java. In fact, it can
the two languages, when used in combination, ideal for Web and distributed enterprise
do pretty much anything Java can because it compiles to Java and uses the Java class libraries. With Python, you
application development.
can create animated Web pages, automate monotonous jobs, and write Internet-interactive programs.
This tutorial begins with coverage of some of the basics of Python programming. Using

Java and Python


plenty of skill-building exercises and interactive programming sessions, this book will

help those new to programming develop an understanding of concepts and practical


techniques.
For experienced
programmers,
theabook
demonstrates
of and
No doubt you've heard
of Java, even
the novices among
you. Over
thousand
books onPython's
it are onbreadth
bookstore
capabilities
and
shows
the
ways
that
Python
interfaces
with
Java
APIs
for
professional
library shelves, so it's hard to miss.
application development.
Remember our discussion of compilers and interpreters? Like Python, Java is an interpreted language, but, like
Python
Programming
the Java(TM)
Libraries:
A Tutorial
for Building
Web
C++, it's also a compiled
language.
In otherwith
words,
it compilesClass
into an
intermediate
language
called bytecode,
and Enterprise
Applications
with Jython
covers
topics
such
which is then interpreted
into machine
code at runtime
(that is,
whenimportant
the program
is put
to as:
use by the user). This
makes Java a hybrid; its ability to be both interepreted and compiled gives it flexibility as well as speed.
Fundamental
programming
concepts,
statements,
expressions,
Java is popular among programmers
because
of its versatility
andincluding
because it's
a much easier
language than C++.
interpreters,
andsimplicity
compilersdepartment. In fact, its complexity, along with its client-side
Still, it's a far cry from Visual
Basic in the
speed and graphics problems, has allowed other languages, such as DHTML (that is, HTML combined with
Python
basics,
includingnumber
operators,
string formatting,
namespaces,
classes, errors,
VBScript and/or JavaScript),
to lure
a substantial
of developers
away from
the Java camp.
and exceptions
None of this means that Java doesn't have the potential to become an excellent client-side development tool. I
Object-oriented
programming
concepts
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
File input/output
for beginning programmers to master quickly and yet powerful enough to keep experienced programmers
interested.
Python's intrinsic functions

Jython

Formatting, parsing, and manipulating strings

Interfacing with the Java APIs and working with Java Streams
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 Python
Java andand
so Java
can compile
bytecode.
Using
Swing totocreate
GUIsThis 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 makeWorking
it applicable
more
with in
SQL
andenvironments.
JDBC(TM) 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.)
Python and Java applets
The Object Management Group (OMG) has adopted Python as one of the scripting component languages of
addition, object
the book
contains
instructions
for downloading
installing
the Python
CORBA, a standard In
distributed
model.
In fact,
CorbaScript,
which is alsoand
a standard
script,
is one of
language
Java with
Development
Kit (JDK).
Python's close cousins.
Pythonand
alsothe
works
ActiveX (also
knownTerminology,
as COM+), adefinitions,
nonstandardexplanations,
distributed
andships
numerous
code samples
makesystems,
this bookand
a useful
learning experience.
component model that
with Windows
operating
with JavaBeans
and RMI, which is a
distributed object model for Java applications. With the addition of the OMG's CORBABean specification,
Whether
youaare
a sophisticated
computer
usermodel,
new toPython
programming
or a serious
which effectively gives
CORBA
client-side
tool-able
component
can be used
to script CORBA
application developer, Python Programming with the Java(TM) Class Libraries will
objects as well.
give you insight into the power of Python and the know-how to put it to work.
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

777

becoming the standard


for scripting
together with
components
fromClass
CORBA,
JavaBeans,
Enterprise
JavaBeans, and
Python
Programming
the Java
Libraries:
A Tutorial
for Building
ActiveX.
Web and Enterprise Applications with Jython
By Richard Hightower
Publisher: Addison Wesley

For Programmers
and Novices: Jython Focus
Pub Date: June 28, 2002
Table
of
Our focus
will be
Contents

ISBN: 0-201-61616-5

primarily
on Jython, rather than on CPython (the non-Java version). Either
Pages: 640
Jython or CPython can be used for an understanding of the core aspects of Python, but you'll
definitely needCharacterized
the Java version
when
to JFC/Swing,
applets,
and
the like.
by ease
of we
use,get
richness
of expression,
and
concise
syntax, Python has
remained a premier programming language for more than a decade, and is used by
novices
and professionals
closetake
relationship
to Java(TM)
You know the old saying
"Every
journey beginsalike.
withIntheparticular,
first step."itsLet's
that first step
now. makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.

Starting with Python

This tutorial begins with coverage of some of the basics of Python programming. Using
To install Python youplenty
must of
have
a recent version
of the
Java
Development
Kit (JDK).
For installation
skill-building
exercises
and
interactive
programming
sessions,
this book details,
will
refer to Appendix A.help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
Now you're up and running.
I'm going
to assume
thatthat
you're
sitting
at the keyboard
with
thisfor
book
situated so that
capabilities
and shows
the ways
Python
interfaces
with Java
APIs
professional
you can follow alongapplication
with the interactive
sessions.
This
is
critical
even
if
you
don't
understand
the
topic under
development.
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
soonProgramming
will.
Python
with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

Python Interactive Mode


Fundamental programming concepts, including statements, expressions,
This section explains how interpreters,
to use Pythonand
in interactive
compilers 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.
Python
basics, including
operators, string formatting, namespaces, classes, errors,
and exceptions
To get Python going, at the DOS prompt (or the equivalent for your operating system) type Python (for
CPython) or Jython (forObject-oriented
the Java-enabled
version). You
should see a welcome message showing the Python
programming
concepts
version number and a copyright notice.
File input/output

C:\Jython>jython
Jython 1.1 on jdk1.3
Python's intrinsic functions
Copyright 1997-1998 Corporation for National Research Initiatives
Formatting, parsing, and manipulating strings
>>>
Interfacing
withcommand,
the Java APIs
andas
working
with Java
Streams
This is followed by a prompt
for your first
known
the primary
prompt
and denoted by >>>. If you
enterprint"Hello World" here and then hit the Enter key, Python will obey your command and print
Python and Java Swing to create GUIs
"Hello World" to theUsing
monitor.
with SQL and JDBC(TM)
>>> print "Hello Working
World"
Hello World
Python and Java applets
>>>
In addition, the book contains instructions for downloading and installing the Python
If that's all you want Python to do at this point, you can exit the system with another command.
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
>>>raise SystemExit
Whether
you"exception"
are a sophisticated
user new
programming
a serious
This creates what's known
as an
(we'll gocomputer
into exceptions
in to
Chapter
7), whichorgets
you out of
application
developer,
Python
Programming
with
the
Java(TM)
Class
Libraries
will
Python. Another way to exit is to hit the Ctrl key in combination with whichever key your system designates
for
give
you
insight
into
the
power
of
Python
and
the
know-how
to
put
it
to
work.
leaving a session. On Windows this is usually Ctrl-z; on UNIX it's usually Ctrl-d.

777

Basic Functions with Python

The following sections


coverProgramming
how Python deals
with
raw material
of programming:
numbers
and text.
Python
with
thethe
Java
Class Libraries:
A Tutorial
for Building

Numbers

Web and Enterprise Applications with Jython


By Richard Hightower

Publisher:
Addison
Wesley
Python can serve as a simple
calculator.
The
syntax it uses is nearly identical to that used for writing spreadsheet
Pub Date:
Junespreadsheets,
28, 2002
formulas. For novices who've
created
all of this will seem familiar. The same is true for
ISBN:
0-201-61616-5
programmers
who've
worked
with
any
language
that
uses an algebraic syntax, such as Pascal, Fortran, Basic, C,
Table of

Pages:
640
or Java.
Contents

In Python, you enter Characterized


a mathematicalbyformula
an expression)
just asand
youconcise
do withsyntax,
spreadsheets,
ease of (called
use, richness
of expression,
Python and
has you're
given a resulting value.
In programming
terms, an expression
is for
a Python
statement
that returns
a value.
remained
a premier programming
language
more than
a decade,
and is used
by That
value is printed to the
console.
novices
and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
Python'sexpression syntax
is straightforward.
application
development. The addition (+), subtraction (), multiplication (*), and division
(/) operators work just like they do in spreadsheets and other programming languages. Parentheses work
similarly as well, forThis
grouping.
tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
>>> (2*2)/4 help those new to programming develop an understanding of concepts and practical
1
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
The equal sign (=) assigns a value to a variable. In the first line of the following example, the variable is
application development.
annual_salary, to which we assign a value of 20000. (My convention is to join two-word variable
names with an underscore.)
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

>>> annual_salary = 20000


>>> monthly_salary = annual_salary/12
>>> monthly_salary
Fundamental programming concepts, including statements, expressions,
1666
interpreters, and compilers
>>> bosses_salary = annual_salary * 3
>>> bosses_salaryPython basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
60000

Object-oriented
programming
In the second line, we divide
annual_salary
by 12 concepts
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 ofFile
thatinput/output
variable to the console. We can use annual_salary again in assigning a
value to bosses_salary.
Python's intrinsic functions
Formatting, parsing, and manipulating strings

For Programmers:
Implicit
Variable
Interfacing with the Java
APIs and working
with JavaDeclaration
Streams
Python declared.
and Java Swing
create
In Python variables Using
are implicitly
That is,tothe
first GUIs
time a variable is used it is assigned a
value. This assigned value determines its type. In the salary example, all variables are assigned
Working
values of type Integer
. with SQL and JDBC(TM)
Pythonthis
andnote
Javaand
applets
Novices, if you're reading
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
In addition,
the book contains
downloading
numbers can be
of type Integer
; text caninstructions
be of types for
String
,Listand
, etc.installing
Basically,the
thePython
type
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
assigned to a variable tells Python what values it can have and what operations can be performed
and numerous code samples make this book a useful learning experience.
on it.
Whether you are a sophisticated computer user new to programming or a serious
The values assigned application
to the variables
we've seen
so Programming
far have been whole
numbers.
Python
also work
developer,
Python
with the
Java(TM)
Classcan
Libraries
willwith
decimals, known in programming
as
floating-point
numbers
(of
type
Float
).
give you insight into the power of Python and the know-how to put it to work.

>>> sum=1.3 + 1.4 + 1.56 + 1.7 + 1.2 + 1.9


>>> mean = sum /6
>>> mean

777

1.51
>>>

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

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 Publisher:
line, we create
a new variable called mean, to which we assign as its value the value of
Addison Wesley
sum divided by 6. In the third line, we enter the variable mean, and Python displays its value to the console.
Pub Date: June 28, 2002

Table of
Text

Contents

ISBN: 0-201-61616-5
Pages: 640

Python, like all programming


languages,
with
text asofstrings
of characters;
individual
delimited
Characterized
by easeworks
of use,
richness
expression,
and concise
syntax,strings
Pythonare
has
by quotes. Take a look
at the following
example: language for more than a decade, and is used by
remained
a premier code
programming
novices and professionals alike. In particular, its close relationship to Java(TM) makes
>>> Name = "James
Agular"
the two languages,
when used in combination, ideal for Web and distributed enterprise
>>> HelloGreeting
= development.
"Hello " + Name + ", how are you?"
application

>>> print HelloGreeting


Hello James Agular,
you? of some of the basics of Python programming. Using
This tutorial how
beginsare
with coverage
>>>
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
In the first line, we create
a variable
called Nameprogrammers,
and assign as the
its value
the string "James
techniques.
For experienced
book demonstrates
Python'sAgular"
breadth of . In the
second line, we create
a variableand
called
HelloGreeting
andinterfaces
assign as with
its value
string
"Hello" plus
capabilities
shows
the ways that Python
Javathe
APIs
for professional
the value of Name plus
"how development.
are you?". Note that this value is made up of three strings joined by two
application
plus (+) signs. This is known as concatenation, which is a fancy term for the simple act of "stringing" strings
together. In the thirdPython
line, weProgramming
ask Python towith
printthe
HelloGreeting
, which it
in the
line.Web
Java(TM) Class Libraries:
A does
Tutorial
forfourth
Building
and Enterprise Applications with Jython covers important topics such as:
Indexing
Fundamental programming concepts, including statements, expressions,
As in Java and C, we can work with individual characters in a string. To access them we use indexing, in which
interpreters, and compilers
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.namespaces,
We can referclasses,
to theseerrors,
as "0
Python
basics,
including
operators,
string
formatting,
index" and "1 index." The numbers
assigned
to
characters
in
a
string
are
referred
to
as
the
string's
indexes.
and exceptions
The following example should
give you a clear
picture ofconcepts
indexing.
Object-oriented
programming

>>> sample = "abcdefghijklmnopqrstuvwxyz"


File input/output
>>> sample
'abcdefghijklmnopqrstuvwxyz'
Python's intrinsic functions
>>> sample[1]
'b'
Formatting, parsing, and manipulating strings
>>> sample[0]
Interfacing with the Java APIs and working with Java Streams
'a'
Using
andsample[1]
Java Swing to. Next
createwe
GUIs
Here we first want the letter
b, soPython
we enter
want the letter a, so we enter
sample[0]. Notice that the indexes are indicated by square brackets.
Working with SQL and JDBC(TM)
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
Python
and Java applets
example above is 25, not 26
.
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
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, whichWhether
we'll getyou
to shortly)
and extract the
"slice" user
you want
toprogramming
work with. or a serious
are a sophisticated
computer
new to
application developer, Python Programming with the Java(TM) Class Libraries will
Let's look at an example:
give you insight into the power of Python and the know-how to put it to work.
Slice Notation

>>> alphabet = "abcdefghijklmnopqrstuvwxyz"


>>> AthruD = alphabet[0:4]
>>> AthruD

777

'abcd'

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
first line assignsBy
the
letters Hightower
of the alphabet to the variable alphabet ; the second line assigns the value
Richard

The
of
indexes 0 through 3 to the variable AthruD; the third line instructs Python to output AthruD; the fourth line
is the result: 'abcd'. Publisher: Addison Wesley
Pub Date: June 28, 2002
Another way to write the
slice [0:4] is as [:4]. An omitted first index tells Python to start at zero. In the
ISBN: 0-201-61616-5
same way,
[1:]
tells
Python
to start at index 1 and make the rest of the string the slice. The following example
Table of

Pages: 640
uses the
slice notation in all three ways: without a first index in the first line; with both indexes in the fourth line;
Contents
and without the second index in seventh line. Table 1-1 describes each of these slices in English.
Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
>>> AthruD= alphabet[:4]
>>> AthruD novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
'abcd'
application development.

Table 1-1. Slice Notation


This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
Slice
help those new Meaning
to programming develop an understanding of concepts and practical
AthruD=alphabet[:4]
the variable
AthruD
from demonstrates
the first character
upbreadth
to but not
techniques. ForAssign
experienced
programmers,
the book
Python's
of
4 index,
i.e., index
0 through
index
3. for professional
capabilities andincluding
shows thethe
ways
that Python
interfaces
with Java
APIs
application development.
EthruM=alphabet[4:13]
Assign the variable EthruM from the 4 index up to but not including
the 13 index.
Python Programming
Java(TM)
Class Libraries:
A Tutorial
Web the
NthruZ=alphabet[13:]
Assignwith
the the
variable
NthruZ
from the 13
index upfor
toBuilding
and including
and Enterprise last
Applications
with
Jython
covers
important
topics
such
as:
character in this string.

>>> EthruM = alphabet[4:13]


>>> EthruM
Fundamental programming concepts, including statements, expressions,
'efghijklm'
interpreters, and compilers
>>> NthruZ = alphabet[13:]
Python basics, including operators, string formatting, namespaces, classes, errors,
>>> NthruZ
'nopqrstuvwxyz' and exceptions
>>> alphabet2 = AthruD + EthruM + NthruZ
Object-oriented programming concepts
>>> alphabet2
'abcdefghijklmnopqrstuvwxyz'
File input/output
>>> alphabet
'abcdefghijklmnopqrstuvwxyz'
Python's intrinsic functions
Formatting, parsing, and manipulating strings

The
Interfacing with the Java
APIsSlice
and working with Java Streams
Using
Python
Java
Swing
create
GUIs the second index. Thus, a slice
In a slice notation, the
range
of theand
slice
is up
to buttonot
including
of[2:5] actually means the second through the fourth characters in a string.
Working with SQL and JDBC(TM)
Lists

Python and Java applets

In addition, the book contains instructions for downloading and installing the Python
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
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and can contain either strings or numbers. Lists are somewhat like arrays in Java or C, except that they can
and numerous code samples make this book a useful learning experience.
contain values of different types.
Whether you are a sophisticated computer user new to programming or a serious
The following example shows how a list uses slice notation:
application developer, Python Programming with the Java(TM) Class Libraries will
you insight into the power of Python and the know-how to put it to work.
>>> letters =give
"abcdefghijklmnop"

>>> numbers = "123456789"


>>> list = [letters, numbers, 1, 2, 3, 4, 5, 1.0, 2.0, 3.0, 4.0]
>>> list[0]
'abcdefghijklmnop'

777

>>> list[1] Python Programming with the Java Class Libraries: A Tutorial for Building
'123456789' Web and Enterprise Applications with Jython
>>> list[2] ByRichard Hightower
1
>>> list[7]
Publisher: Addison Wesley
1.0
Pub Date: June 28, 2002
>>> list[:]
ISBN: 0-201-61616-5
Table of
['abcdefghijklmnop',
'123456789', 1, 2, 3, 4, 5, 1.0, 2.0, 3.0, 4.0]

Pages: 640
>>> Contents
len(list)
11
Characterized by ease of use, richness of expression, and concise syntax, Python has
>>> list = ["hello",
"goodbye"]
remained a premier
programming language for more than a decade, and is used by
>>> list[0:2]novices and professionals alike. In particular, its close relationship to Java(TM) makes
['hello', 'goodbye']
the two languages, when used in combination, ideal for Web and distributed enterprise
>>>len (list)application development.
2
This tutorial begins with coverage of some of the basics of Python programming. Using
of skill-building
Python as aplenty
Main
Programexercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
In interactive mode, capabilities
you work with
instruction
at a time.
When with
it's setJava
up as
a standalone
program
andPython
shows one
the ways
that Python
interfaces
APIs
for professional
(i.e., not needing user
interaction),
Python
performs
any
number
of
consecutive
tasks.
Just
turn
it
on,
and
it does
application development.
all the rest. To use Python this way, you first have to write a program and then save it as a text file.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
Enter the following at
your
console Applications
and save it aswith
campPython.py.
and
Enterprise
Jython covers important topics such as:

print "hello mother"


print "hello father"
Fundamental programming concepts, including statements, expressions,
print "greetings interpreters,
from camp
Python"
and compilers
Go to the command promptPython
and enter
Jython
campPython.py
.
basics,
including
operators, string formatting,
namespaces, classes, errors,

and exceptions

C:\book\chap1>jython campPython.py
The output is

Object-oriented programming concepts


File input/output

hello mother
hello father
Python's intrinsic functions
greetings from camp Python
Formatting, parsing, and manipulating strings
Essentially, you've created a module called campPython.py, and the text you typed in is the module's main
methodthe code that's executed
first.with the Java APIs and working with Java Streams
Interfacing
Now take a look at the nextUsing
code Python
example.
represents
module
a class called Camp, a method
andIt Java
Swingato
create containing
GUIs
calledSayHello(), and a function called sayCampHello().
Working with SQL and JDBC(TM)

class Camp:
Python and Java applets
def sayHello(self):
return "\n Hello Mom \n Hello Dad"
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
def sayCampHello():
numerous code samples make this book a useful learning experience.
camp = and
Camp()

print ("Hello: " + camp.sayHello())

Whether you are a sophisticated computer user new to programming or a serious


application developer, Python Programming with the Java(TM) Class Libraries will
if __name__ == "__main__":
give you insight into the power of Python and the know-how to put it to work.

sayCampHello()

777

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 ifPython


__name__=="__main__":
indicates
that
this part A
ofTutorial
the module
be
Programming with the Java
Class
Libraries:
forshould
Building
executed if this scriptWeb
is run
as Enterprise
the main program
(from the
command
and
Applications
with
Jythonprompt example).
By Richard Hightower

For Programmers Only


Publisher: Addison Wesley
Pub Date:
June 28,two
2002
Novices, go ahead and read
the following
subsections if you like, but they're way over your head right now.
Table of
Blocks
Code
Contents

ISBN: 0-201-61616-5
Pages: 640

Characterized
by ease
use,
richness
of expression,
syntax, Python
In the Camp example,
notice that the
classof
and
function
definitions
don't and
haveconcise
block delimiters
but arehas
delimited
remained
a
premier
programming
language
for
more
than
a
decade,
and
is
used
by the
by whitespace only. In Python, indentation defines code blocks, so all Python programs look pretty much
alike.such
In particular,
closeBasic,
relationship
to Java(TM)
makes
same. This is in real novices
contrastand
withprofessionals
other languages,
as C++ orits
Visual
in which
three different
the
two
languages,
when
used
in
combination,
ideal
for
Web
and
distributed
enterprise
programmers can come up with three different styles for the same program. You should understand the issue if
development.
you've ever written aapplication
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.
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
Passing Arguments to a Program
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
If you're writing a utility
application,
you might
wantthat
to bePython
able tointerfaces
pass command-line
arguments
to the program.
capabilities
and shows
the ways
with Java APIs
for professional
In Python, we do thisapplication
by putting development.
the arguments on the command line after the script.

C:\book\chap1>jython
args.py
hello
howClass
are
you A Tutorial for Building Web
Python Programming
with the
Java(TM)
Libraries:
and Enterprise Applications with Jython covers important topics such as:
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.
Fundamental
programming concepts, including statements, expressions,
interpreters, and compilers

import sys
print(sys.argv[0])
Python basics, including operators, string formatting, namespaces, classes, errors,
print(sys.argv[1])
and exceptions
print(sys.argv[2])
print(sys.argv[3])
Object-oriented programming concepts
print(sys.argv[4])
File input/output
The first line of args imports the sys module. The second through sixth lines place each command-line argument
Python's
intrinsic
functionsoutput:
in the sys.argv list. This
produces
the following

args.py
hello
how
are
you

Formatting, parsing, and manipulating strings


Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs

Working with SQL and JDBC(TM)


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:]
Python and Java
applets
indicates the 1 index through the end of the argv list.
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
Back to Basics
and numerous code samples make this book a useful learning experience.
If you're working in a Python program, you can switch to interactive mode with the -i command-line argument,
Whether you are a sophisticated computer user new to programming or a serious
which allows the script to be interpreted and then inspected by the interactive interpreter. You'll be glad to have
application developer, Python Programming with the Java(TM) Class Libraries will
this feature if there's a bug in your code that you need to find and fix.
give you insight into the power of Python and the know-how to put it to work.
The following code is our campPython.py module, this time with the -i inserted before the module name in the
first line.

777

C:\book\chap1>jython -i campHello2.py

Hello:
Python Programming with the Java Class Libraries: A Tutorial for Building
Hello Mom Web and Enterprise Applications with Jython
Hello Dad ByRichard Hightower
>>> camp = Camp()
>>> print camp.sayHello()
Publisher: Addison Wesley
Pub Date: June 28, 2002

Hello Mom
Table Dad
of
Hello

>>> Contents

ISBN: 0-201-61616-5
Pages: 640

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
The Fast Track
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
Python supports control flow, functions, exception handling, object-oriented programming, and more, much like
application development.
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 This
Java,tutorial
JavaScript,
andwith
C++.
begins
coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities
and shows
the ways
that Python
interfaces
withaJava
APIsa for
professional
Python is a dynamically
typed language,
similar
to Smalltalk.
When
you assign
variable
value,
that value
application
development.
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
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
manipulated.
and Enterprise Applications with Jython covers important topics such as:
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).
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
Numeric Types

Types

Python basics, including operators, string formatting, namespaces, classes, errors,


Numeric types are objects in
The built-in function type() indicates the type, as the following code
andPython.
exceptions
snippet illustrates:
Object-oriented programming concepts

>>> myInt = 1
>>> type(myInt) File input/output
<jclass org.python.core.PyInteger>
Python's intrinsic functions

>>> myFloat = 1.1


>>> type(myFloat)Formatting, parsing, and manipulating strings
<jclass org.python.core.PyFloat>

Interfacing with the Java APIs and working with Java Streams

>>> myLong = 1l Using Python and Java Swing to create GUIs


>>> type(myLong)
<jclass org.python.core.PyLong>
Working with SQL and JDBC(TM)
You can add, subtract, divide,
andand
multiply
numeric types.
Python
Java applets

>>>
>>>
2
>>>
>>>
2

num = 1 +In addition,


1
the book contains instructions for downloading and installing the Python
print numlanguage and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.

average = (1+2+3)/3
print average
Whether you are a sophisticated computer user new to programming or a serious

application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.
Chapter 2 will tell you more about Python built-in types. Chapter 3 will tell you about Python-supported
operators.
Collection Types

777

Programming
Java
Class Libraries:
A Tutorial
for Building
Python supports fourPython
main built-in
collectionwith
types:the
strings,
dictionaries,
lists, and
tuples. Strings,
lists, and tuples
Web and Enterprise Applications with Jython
are called sequences, for which Python provides many built-in operations. If you know Java, think of a list as a
By Richard Hightower
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
Publisher: Addison Wesley
collections, which makes
the code that works with them easier to write and understand. Java has no such syntax.
Pub Date: June 28, 2002
ISBN:how
0-201-61616-5
The example that follows shows
to declare an instance of each collection type.

>>>
>>>
>>>
>>>

Table of
Contents

Pages: 640

list = [1,2,3,4,5,6]
tuple = (1,2,3,4,5,6)
Characterized by ease of use, richness of expression, and concise syntax, Python has
string = remained
"123456"
a premier programming language for more than a decade, and is used by
dict = {"one":1,
"two":2,alike.
"three":3,
"five":5,
"six":6}
novices and professionals
In particular, its"four":4,
close relationship
to Java(TM) makes

the two languages, when used in combination, ideal for Web and distributed enterprise
Here are the corresponding
type development.
names for each collection variable:
application

>>> type(list)
This tutorial begins with coverage of some of the basics of Python programming. Using
<jclass org.python.core.PyList>
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical

>>> type (tuple)


techniques. For experienced programmers, the book demonstrates Python's breadth of
<jclass org.python.core.PyTuple>
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.

>>> type(string)
<jclass org.python.core.PyString>
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

>>> type(dict)
<jclass org.python.core.PyDictionary>
Fundamental programming concepts, including statements, expressions,
interpreters,
compilers
Also like Perl and Visual Basic,
Pythonand
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:
Python basics, including operators, string formatting, namespaces, classes, errors,
>>> for item in list:
and exceptions

...
...
1
2
3
4
5
6

print item
Object-oriented programming concepts
File input/output
Python's intrinsic functions
Formatting, parsing, and manipulating strings

Interfacing with the Java APIs and working with Java Streams
Here's the same for loop for a string and a tuple, respectively:
Using Python and Java Swing to create GUIs

>>> for item in string:


...
print item
Working with SQL and JDBC(TM)
...
Python and Java applets
1
2
In addition, the book contains instructions for downloading and installing the Python
3
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
4
and numerous code samples make this book a useful learning experience.
5
6
Whether you are a sophisticated computer user new to programming or a serious
developer, Python Programming with the Java(TM) Class Libraries will
>>> for item application
in tuple:
give
you
insight
into the power of Python and the know-how to put it to work.
...
print item

...
1
2
3

777

4
5
6

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

Note the indentation that


marks the body of the for statement in all three examples. (Chapter 4 deals with for
Publisher: Addison Wesley
loops and for statements.)
Pub Date: June 28, 2002

0-201-61616-5
All of Table
the Python
collectionISBN:
types can
be indexed using the [ ] notationjust like an array in Java or C. The
of

Pages: 640
following
example shows how for lists, tuples, and strings:
Contents

>>> list[1] Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
2
>>> tuple[1] novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
2
>>> string[1]application development.
'2'

This tutorial begins with coverage of some of the basics of Python programming. Using
skill-building
exercises and interactive programming sessions, this book will
With dictionaries youplenty
use aofkey
to index a value.
help those new to programming develop an understanding of concepts and practical
>>> dict["one"]
techniques. For experienced programmers, the book demonstrates Python's breadth of
1
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
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 willPython
throw Programming
an exception. with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
You can use the index to change the value held by a list or a dictionary at that index.

>>> list [0]=0 Fundamental programming concepts, including statements, expressions,


>>> print list interpreters, and compilers
[0, 2, 3, 4, 5, 6]
Python basics, including operators, string formatting, namespaces, classes, errors,
>>> dict["one"]=0and exceptions

>>> print dict


programming
concepts
{'one': 0, 'six':Object-oriented
6, 'two':
2, 'five':
5, 'three': 3, 'four': 4}
File or
input/output
You can't do this with a string
tuple because these collection types are immutable.
Python's intrinsic
functions
Strings can be added and multiplied.
Here's an
example of addition:
Formatting,
parsing, and manipulating strings
>>> string2 = string
+ "789"
>>> print string2
Interfacing with the Java APIs and working with Java Streams
123456789
Using Python and Java Swing to create GUIs
Here's an example of multiplication:
Working with SQL and JDBC(TM)

>>> string2 = string * 2


>>> print string2Python and Java applets
123456123456

In addition, the book contains instructions for downloading and installing the Python

>>> print string


language and the Java Development Kit (JDK). Terminology, definitions, explanations,
123456
and numerous code samples make this book a useful learning experience.
Addition and multiplication
lists and tuples.
Whetheralso
youwork
are a for
sophisticated
computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
>>> list = list
+ insight
[7, 8,
give you
into 9]
the power of Python and the know-how to put it to work.

>>> list
[0, 2, 3, 4, 5, 6, 7, 8, 9]

777

>>> tuple = tuple + (7,8,9)

>>> tuple
Python Programming with the Java Class Libraries: A Tutorial for Building
(1, 2, 3, 4, Web
5, and
6, Enterprise
7, 8, 9)
Applications with Jython
By Richard Hightower

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
Publisher:
Addison
Wesley
on built-in functions andPub
operations.
Date: June 28, 2002
Table Flow
of
Control

Contents

ISBN: 0-201-61616-5
Pages: 640

Characterized
by ease
of use, richness
of in
expression,
syntax, Python
has is
Python provides all of
the control flow
constructs
(discussed
Chapter 4)and
thatconcise
an experienced
programmer
used to: if,whileremained
, and fora. premier
The onlyprogramming
difference between
these
Python and
counterparts
in
language
forconstructs
more thanina decade,
andtheir
is used
by
novices
and
professionals
alike.
In
particular,
its
close
relationship
to
Java(TM)
makes
other languages is their use of indentation to define code blocks.
the two languages, when used in combination, ideal for Web and distributed enterprise
Here's a simple if statement.
that, unlike Java, Python uses numerics as Boolean values; thus, any nonzero
applicationNote
development.
value is considered true.
This tutorial begins with coverage of some of the basics of Python programming. Using
>>> var1=1 plenty of skill-building exercises and interactive programming sessions, this book will
>>> if var1: help those new to programming develop an understanding of concepts and practical
...
printtechniques.
"hello"
For experienced programmers, the book demonstrates Python's breadth of
...
capabilities and shows the ways that Python interfaces with Java APIs for professional
hello
application development.
Here's a more complex
if statement
that uses
("else if")
andLibraries:
else blocks:
Python
Programming
with elif
the Java(TM)
Class
A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

>>> var1 = 1
>>> if var1==1:
...
print "Hello"
Fundamental programming concepts, including statements, expressions,
... elif var1==2:interpreters, and compilers
...
print "Goodbye"
Python basics, including operators, string formatting, namespaces, classes, errors,
... else:
and exceptions
...
print "Later
on"
...
Object-oriented programming concepts
Hello
input/output
You see that, if the first testFile
passes
(var1 == 1:), the second (var1 == 2:) doesn't execute, even
though both may be true.
Python's intrinsic functions

while statements work as expected. The back quotes get a string representation of var1.
Formatting, parsing, and manipulating strings

>>> while var1 > 10:


Interfacing with the Java APIs and working with Java Streams
...
print "var1 = " + 'var1'
...
var1 = var1
10 and Java Swing to create GUIs
Using -Python
...
var1 = 100
Working with SQL and JDBC(TM)
var1 = 90
Python and Java applets
var1 = 80
var1 = 70
In addition, the book contains instructions for downloading and installing the Python
var1 = 60
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
var1 = 50
and numerous code samples make this book a useful learning experience.
var1 = 40
var1 = 30
Whether you are a sophisticated computer user new to programming or a serious
var1 = 20

application developer, Python Programming with the Java(TM) Class Libraries will
giveloop
youtoinsight
the power
of Python
to put
it to work.
Earlier we used a for
iterateinto
through
a collection.
Theand
usethe
of know-how
for in a more
traditional
fashion requires
thexrange() built-in function. The following Python example is equivalent to the one that follows it, which
uses a basic C-like syntax.

777

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

...
...

printPython
`index`
Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

for(int index = 0; index < 100; index += 10){


Publisher: Addison Wesley

System.out.println(index)
Pub Date: June 28, 2002
}
Table of

youContents
leave out the

ISBN: 0-201-61616-5
Pages: 640

If
10 in the call to xrange() , it defaults to incrementing by 1. Thus, the following example
iterates 100 times (0100).
Characterized by ease of use, richness of expression, and concise syntax, Python has
a premier programming
>>> for indexremained
in xrange(0,
100): language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
two languages,
whenChapter
used in4,combination,
Chapter 3 deals withthe
comparison
operators;
with controlideal
flow.for Web and distributed enterprise
application development.

Exception Handling
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
Like so much of Python,
is a lot like
its counterparts
in otheroflanguages.
Forpractical
example,
help exception
those new handling
to programming
develop
an understanding
concepts and
Python'stry clause techniques.
is like Java'sFor
try
, and its except
clausethe
is like
catch. Python's
Considerbreadth
an exception
experienced
programmers,
bookJava's
demonstrates
of
thrown by a dictionary
object if we
a nonexistent
In this case,
the interpreter
prints
the exception
capabilities
andtry
shows
the ways key.
that Python
interfaces
with Javasimply
APIs for
professional
out to the screen. application development.

>>> dict = {"Green


Eggs":"Ham"}
Python Programming
with the Java(TM) Class Libraries: A Tutorial for Building Web
>>> dict["Blue
Eggs"] Applications with Jython covers important topics such as:
and Enterprise
Traceback (innermost last):
File "<console>", line 1, in ?
Fundamental programming concepts, including statements, expressions,
KeyError: Blue Eggs
interpreters, and compilers
To handle this exception we can do this:
Python basics, including operators, string formatting, namespaces, classes, errors,
>>> try:
and exceptions

...
dict["Blue Eggs"]
Object-oriented
programming concepts
... except KeyError,
error:
...
print "Sam, Blue Eggs do not go with Ham " + 'error'
File input/output
...
Python's intrinsic functions

Sam, Blue Eggs do not go with Ham <exceptions.KeyError instance at


-864407725>
Formatting, parsing, and manipulating strings
KeyError refers to the class
of the exception
thatAPIs
we want
to catch, with
and error
refers to the instance of
Interfacing
with the Java
and working
Java Streams
KeyError . Here's the equivalent Java pseudocode:
try{

Using Python and Java Swing to create GUIs

dict.index("Blue
Eggs");
Working with SQL and
JDBC(TM)
}
catch(KeyError error){
Python and Java applets
In addition, the book contains instructions
for downloading
andwith
installing
the Python
System.out.println("Sam,
Blue Eggs
do not go
Ham"
language and the Java
Development Kit (JDK). Terminology, definitions, explanations,
+ error);

and numerous code samples make this book a useful learning experience.

C++'s pseudocode isWhether


similar. you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
In addition to try...except
, Python
haspower
a try...finally
block. Its finally
give you insight
into the
of Python and the know-how
to put it to clause
work. 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.

777

Chapter 7 deals with Python exception handling.

Functions

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

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
Publisher: Addison Wesley
procedures, which perform multiple actions.
Pub Date: June 28, 2002

0-201-61616-5
Here'sTable
a function
that sums ISBN:
two numbers
and returns their value:
of

Contents

Pages: 640

>>> def sum(num1, num2):


Characterized
ease of use, richness of expression, and concise syntax, Python has
...
return
num1 + bynum2
remained
a
premier
programming language for more than a decade, and is used by
...
novices
and
professionals
alike. In particular, its close relationship to Java(TM) makes
>>> sum(5,5)
the
two
languages,
when
used
in combination, ideal for Web and distributed enterprise
10
application development.
It shows how Python, like Visual Basic, uses named arguments and default values, which allow customization of
This tutorial begins with coverage of some of the basics of Python programming. Using
function calls.
plenty of skill-building exercises and interactive programming sessions, this book will
>>> def sum(var1=0,
var2=0,
var3=0):
help those new
to programming
develop an understanding of concepts and practical
...
return
var1 For
+ var2
+ var3
techniques.
experienced
programmers, the book demonstrates Python's breadth of
...
capabilities and shows the ways that Python interfaces with Java APIs for professional
>>> sum()
application development.

0
>>> sum(1,1) Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
2
>>> sum(var1=5, var3=5)
10
Fundamental programming concepts, including statements, expressions,
interpreters,
andsum
compilers
Because Python is dynamically
typed, the
function works with numeric types as well as strings.

Python
basics, ",
including
string formatting, namespaces, classes, errors,
>>> sum("Hello, ",
"Mom,
"howoperators,
are you?")
and
exceptions
'Hello, Mom, how are you?'
Object-oriented
programming
A function that doesn't return
a type automatically
returnsconcepts
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.
File input/output
Chapter 5 covers functions in detail.
Python's intrinsic functions

Modules and Packages


Formatting, parsing, and manipulating strings
Interfacing
witha the
Javamodule
APIs and
working
witha cross
Java Streams
If you're from a Java or C++
background,
Python
will
seem like
between a package and a class
with static methods. Modules can contain classes, functions, and data objects. Essentially they're files that
Using Python and Java Swing to create GUIs
contain Python definitionsclasses and functionsand Python statements; they can be imported into other
modules or into the main module.
file names
are appended with the suffix .py.
WorkingModule
with SQL
and JDBC(TM)
Python modules are similarPython
to *.java
look and act very much like Visual Basic modules. See Chapter 5
andfiles
Javaand
applets
to learn more about them. This chapter also discusses Python packages, which help group and organize a set of
related modules.
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Classes and OOP

Whether
you
are a sophisticated
new to programming
or athe
serious
Like their counterparts
in other
languages,
classes in computer
Python areuser
collections
of variables and
methods that
application
developer,
Python
Programming
with
the
Java(TM)
Class
Libraries
operate on them. To illustrate, here's an example class, Car, that inherits from the two other classes,will
you insight into the:power of Python and the know-how to put it to work.
Automobile andgive
Transportation

>>> class Automobile:


...
pass
...

777

>>> class Transportation:


Python Programming with the Java Class Libraries: A Tutorial for Building
...
pass Web and Enterprise Applications with Jython
...
By Richard Hightower
>>> class Car(Automobile, Transportation):
...
make="Ford"
Publisher: Addison Wesley
...
model="Taurus"
Pub Date: June 28, 2002
...
def __init__(self,
make, model):
ISBN: 0-201-61616-5
... Table of
self.make=make
Pages: 640
... Contents
self.model=model
...
def __del__(self):
Characterized by ease of use, richness of expression, and concise syntax, Python has
...
print
"similar
to language
a destructor"
remained
a premier
programming
for more than a decade, and is used by
...
def __str__(self):
novices and professionals alike. In particular, its close relationship to Java(TM) makes
...
str
= "Make
" +inself.make
the two
languages,
when used
combination, ideal for Web and distributed enterprise
...
str development.
= str + ", Model " + self.model
application
...
return str
...
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
We can create an instance
of Car
call it car. develop an understanding of concepts and practical
help those
newand
to programming
techniques. For experienced programmers, the book demonstrates Python's breadth of

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


capabilities and shows the ways that Python interfaces with Java APIs for professional
>>> print car
application development.
Make Chevy, Model Nova
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
And we can show that car is also an instance of classes Car and Automobile.
and Enterprise Applications with Jython covers important topics such as:

>>> print isinstance(car, Car)


1
Fundamental programming concepts, including statements, expressions,
>>> print isinstance(car,
interpreters, andAutomobile)
compilers
1
Python basics, including operators, string formatting, namespaces, classes, errors,
Note that Car defines twoand
methods:
__init__ , which acts as a constructor; and __del__, which acts as a
exceptions
destructor.__str__ returns a string representation of the class.
Object-oriented programming concepts
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
File input/output
Smalltalk.
Python's intrinsic functions
Chapters 5 and 6 cover Python classes. Chapter 9 covers built-in operations and functions that pertain to classes.
Formatting, parsing, and manipulating strings

Working with JavaInterfacing


from Python
with the Java APIs and working with Java Streams
The following interactive session
shows how
to import
Java
classes from Python:
Using Python
and Java
Swingand
to use
create
GUIs
Import the Frame class from
the java.awt
package.
Working
with SQL
and JDBC(TM)

>>> from java.awtPython


import
Frame
and Java
applets
Create an instance ofInFrame
, named
frame
. instructions for downloading and installing the Python
addition,
the book
contains
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
>>> frame = Frame("My
first
frame
created
in learning
Jython")
and numerous code
samples
make this
book a useful
experience.
Callframe'ssetVisible()
Whether you method
are a sophisticated computer user new to programming or a serious

application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

>>> frame.setVisible(1)

Import the Button class from java.awt.

777

>>>from java.awt import Button

Create an instance ofPython


Button
, called hit_me
Programming
with. the Java

>>>hit_me =

Class Libraries: A Tutorial for Building


Web and Enterprise Applications with Jython
Button
("Hit me!")
By Richard Hightower

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


Publisher: Addison Wesley

Pub Date: June 28, 2002


>>>def hit_me_event_handler(event):
ISBN: 0-201-61616-5
... Table ofprint "Ouch!"

Pages:
640
... Contents

by ease of use, richness of expression, and concise syntax, Python has


Register the handler Characterized
with the function.
remained a premier programming language for more than a decade, and is used by
>>>hit_me.actionPerformed
= hit_me_event_handler
novices and professionals
alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
Addbutton to frame
by calling
frame'sadd() method.
application
development.

>>> frame.add(hit_me)
This tutorial begins with coverage of some of the basics of Python programming. Using
java.awt.Button[button0,0,0,0x0,invalid,label=Hit
plenty of skill-building exercises and interactive programmingme!]
sessions, this book will
help those new to programming develop an understanding of concepts and practical
Callframe'spack() method so that the button will be visible.
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
>>>frame.pack()
application development.
Click the button with the mouse and watch the output in the interactive interpreter.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise
Applications
with Jython covers important topics such as:
Chapter 11 covers working
with Java
APIs from Python.

The Power of Python


Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
Python can make tough tasks trivial. Let's prove this by an example. How many lines of code will it take you in
Python
including
string
formatting,
namespaces, classes, errors,
your favorite language to parse
thebasics,
following
string operators,
and put each
value
in a variable?
and exceptions

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


Object-oriented programming concepts

FileMaybe
input/output
Can you parse it in ten lines?
five? Python can do it in one (not including the import statement).
Python's intrinsic
>>>from string import
splitfunctions
>>>name, phone, email = split(str, ",")

Formatting, parsing, and manipulating strings

This is what we get:

Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs

>>> print name


Rick Hightower Working with SQL and JDBC(TM)
>>> print phone
555-1212
Python and Java applets
>>> print email
In addition, the book contains instructions for downloading and installing the Python
rick_m_hightower@emailcompany.com
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
>>>
and numerous code samples make this book a useful learning experience.
you are function
a sophisticated
computer
user new
to programming
or a serious
Simple parsing usingWhether
the split()
is covered
in Chapter
10; more
advanced parsing
using regular
application
developer,
Python Programming with the Java(TM) Class Libraries will
expressions is covered
in Appendix
E.
give you insight into the power of Python and the know-how to put it to work.
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.

777

>>> v = "%(name)s's phone number and email is %(phone)s and %(email)s" %

locals() #onePython
lineProgramming with the Java Class Libraries: A Tutorial for Building
>>> print v Web and Enterprise Applications with Jython
Rick Hightower's
phone
number and email is 555-1212 and
By Richard
Hightower
rick_m_hightower@emailcompany.com
Publisher: Addison Wesley
Pub Date: June 28, 2002

Chapter 3 covers Python string formatting. It's a lot like string formatting in C, with its sprintf() and
ISBN: 0-201-61616-5
printf()
Table offunctions, so you should pick it up quickly if you have any C background.

Contents

Pages: 640

Characterized
by easeHere?
of use, richness of expression, and concise syntax, Python has
Where Do You
Go from
remained a premier programming language for more than a decade, and is used by
novices
professionals
In particular,
relationship
to want
Java(TM)
makes
If you're an experienced
C++and
programmer
you alike.
can skip
to Chapterits
8, close
although
you might
to skim
Chapters
the
two
languages,
when
used
in
combination,
ideal
for
Web
and
distributed
enterprise
2 through 7 and use them as a reference. Visual Basic programmers can skip to Chapter 8 as well, with detours
application programming)
development. and 7 (on exception handling) and a skim of Chapters 2 though
toChapter 6 (on object-oriented
5.

This tutorial begins with coverage of some of the basics of Python programming. Using
plenty with
of skill-building
exercises
andconcentrate
interactive on
programming
this
will
Novice Java programmers
no C experience
should
the last halfsessions,
of Chapter
3 book
(on string
help
those
new
to
programming
develop
an
understanding
of
concepts
and
practical
formatting) and the last half of Chapter 6 (on dynamic polymorphism and operator overloading) and skim
techniques.
For experienced
programmers,
the book
demonstrates
Python's breadth
Chapters 2 through 5.
If you're comfortable
with Java,
see Appendix
C,which
creates equivalent
Java andofPython
capabilities
and
shows
the
ways
that
Python
interfaces
with
Java
APIs
for
professional
programs for comparison.
application development.

Summary

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
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
Fundamental programming concepts, including statements, expressions,
interpreter, you should have a pretty good feel for what programming is. Don't worry if you still feel confused.
interpreters, and compilers
Your confusion will go away after the next few chapters. Once you've read up through Chapter 8, you'll feel
confident using Pythonyou'll
feelbasics,
like a including
programmer.
After that,
we'll
get into the
really fun classes,
stuff: graphical
Python
operators,
string
formatting,
namespaces,
errors,
user interfaces and applets.and exceptions
If you want to learn more about
Python on programming
your own, go to
www.python.org,www.sourceforge.net and
Object-oriented
concepts
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
you can sign up for the email list, view the documentation, visit some of the
Filesites,
input/output
contributor sites, and join a newsgroup.
Python's intrinsic functions

CONTENTS

Formatting, parsing, and manipulating strings


Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs
Working with SQL and JDBC(TM)
Python and Java applets
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
CONTENTS
Web and Enterprise Applications with Jython
By Richard Hightower

Chapter 2. Statements
and Expressions
Publisher: Addison Wesley
Pub Date: June 28, 2002

Comments and Document


Strings
ISBN: 0-201-61616-5
Table of
Statements
Pages: 640
Contents
Expressions
Variables Characterized by ease of use, richness of expression, and concise syntax, Python has
Data Typesremained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
Python Collection
Types when used in combination, ideal for Web and distributed enterprise
the two languages,
Advanced Topic:
Determining
Types at Runtime
application
development.
Literals
Summary This tutorial begins with coverage of some of the basics of Python programming. Using

plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
Terms in This Chapter
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
Assignment development.
application
Key/value pair
Case sensitivity
Python
Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
Literal
and Enterprise Applications with Jython covers
important topics such as:
Class
Method
Collection
type
Fundamental
programming concepts, including statements, expressions,
Module
interpreters, and compilers
Comm ent
Objectformatting, namespaces, classes, errors,
Python basics, including operators, string
Declaration
and exceptions
Operator
Definition
Object-oriented programming concepts
Runtime
Document
string
File input/output
Sequence
EscapePython's
sequence
intrinsic functions
Source code
Expression
Formatting, parsing, and manipulating strings
Statem ent execution
File path
Interfacing with the Java APIs and working with Java Streams
Tuple
Function
Using Python and Java Swing to create GUIs
Type
Immutability
Working with SQL and JDBC(TM)
Value
Initialization
Python and Java applets
Variable
Instance
In addition, the book contains instructions for downloading and installing the Python
Whitespace
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
Key
and numerous code samples make this book a useful learning experience.
In this chapter, we continue our tour of Python with perhaps the most basic feature: statements. We'll also look at
Whether you are a sophisticated computer user new to programming or a serious
data types, comments, variables, and literals.
application developer, Python Programming with the Java(TM) Class Libraries will
you
theYou
power
of Python
and the
know-how to put
it to
Novices, you shouldgive
know
theinsight
drill byinto
now:
learn
to program
by programming,
so try
towork.
follow along with
the interactive sessions in this chapter. If you get stuck on something, just enter in a few of the examples in
Jython and skip the rest. Most of the ideas here will be used through the rest of the book, so what you don't
understand here you may later on in a different context. Go ahead and read the Advanced Topic sections, but
again, don't worry if they confuse you at this point.

777

Python Programming with the Java Class Libraries: A Tutorial for Building

You programmers can skim or skip this chapter. The material hereliterals, variables, and the likeis common
Web and Enterprise Applications with Jython
to almost all languages.
If you do read the chapter through, focus on the parts that are unique to Python,
By Richard Hightower
particularly the section "Python Collection Types" and the Advanced Topic section "Determining Types at
Runtime." Also read the "For Programmers" sidebars.
Publisher: Addison Wesley
Pub Date: June 28, 2002

Comments and Document


Strings
ISBN: 0-201-61616-5

Table of
Contents

Pages: 640

Python has two ways to document, or explain, what your code is doing. One way uses code comments; the other
Characterized by ease of use, richness of expression, and concise syntax, Python has
uses document strings.
remained a premier programming language for more than a decade, and is used by
Comments novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
Comments, unlike the code itself, don't tell Python what to do. They're more like notes to yourself, and to other
programmers who may
to modify
editcoverage
your code
say,basics
"Thisof
is Python
why I wrote
it this way."
In
Thiswant
tutorial
beginsor
with
oflater,
somethat
of the
programming.
Using
Python, a comment starts
with
the
pound
(#)
character,
which
tells
the
interpreter
to
ignore
the
text
after
it
plenty of skill-building exercises and interactive programming sessions, this book willuntil
the end of the line. Each
a comment
must startdevelop
with this
help line
thoseofnew
to programming
ancharacter.
understanding of concepts and practical

techniques. For experienced programmers, the book demonstrates Python's breadth of


As the following example shows, you can put comments on their own line or you can add them after a statement.
capabilities and shows the ways that Python interfaces with Java APIs for professional
application
development.
#The following
example
demonstrates

#printing hello world to the console


Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
print ("hello world") #this prints hello world
and Enterprise Applications with Jython covers important topics such as:

For Programmers:
Comments
in Other
Languages
Fundamental programming
concepts, including
statements,
expressions,
interpreters, and compilers
Visual Basic uses two double quotes ( " ") to indicate a comment, but otherwise it uses comments
basics,Java,
including
formatting,
namespaces,
like Python does; soPython
does UNIX.
C, andoperators,
C++ havestring
two types
of comments.
One isclasses,
similarerrors,
to
and
exceptions
Python's but uses two forward slashes ( //). The other is a multiline comment starting with /* and
ending with */. Python doesn't have a multiline comment style.
Object-oriented programming concepts

Document StringsFile input/output


Python's intrinsic functions
Document strings are literals that you put at the beginning of modules, functions, classes, and methods. Unlike
comments, they're not thrown
away butparsing,
can be displayed
from the strings
interactive interpreter. The following example
Formatting,
and manipulating
(comments.py) shows a document string for a module, a class, and a function, respectively. (We'll get to these in
Chapter 5.)
Interfacing with the Java APIs and working with Java Streams

"""Example showing
a Python
module
document
string
Using
and Java
Swing to create
GUIs for the comments module. This
module document string is multi-line.
Working with SQL and JDBC(TM)
"""
Python and Java applets
class Camp:
"""Example showing a class document string"""
In addition, the book contains instructions for downloading and installing the Python
def sayHello(self):
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
return "\n Hello Mom \n Hello Dad"
and numerous code samples make this book a useful learning experience.

def sayCampHello():
Whether you are a sophisticated computer user new to programming or a serious
"""Example
showing
a Python
function
document
string"""
application
developer,
Programming
with the Java(TM)
Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

camp = Camp()
print ("Hello: " + camp.sayHello())

777

if __name__ == "__main__":

sayCampHello()
Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython

Here's another example.


The __doc__
By Richard
Hightowerattribute of the Camp class and the sayCampHello() function
hold the document strings.
Publisher: Addison Wesley

C:\book\chap2>jython -i comments.py
Pub Date: June 28, 2002
Hello:
ISBN: 0-201-61616-5
Hello
Table Mom
of

Pages:
640
Hello
Dad
Contents
>>> Camp.__doc__
Characterized
by easedocument
of use, richness
of expression, and concise syntax, Python has
'Example showing
a class
string'
remained
a
premier
programming
language
for more than a decade, and is used by
>>> sayCampHello.__doc__
novices
and
professionals
alike.
In
particular,
its close relationship to Java(TM) makes
'Example showing a function document string'

the two languages, when used in combination, ideal for Web and distributed enterprise
development.
Let's say we want to application
learn something
about a module named comments and we don't have the source code. So,
we start a new Jython session, import comments to it, and view its document string.
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
>>> import comments
help those new to programming develop an understanding of concepts and practical
>>> print comments.__doc__
techniques.
For experienced
programmers,
the book
Python's module.
breadth of This module
Example showing
a module
document
string
for demonstrates
the comments
capabilities
and
shows
the
ways
that
Python
interfaces
with
Java
APIs
for
professional
document string is multi-line.
application development.
In the example below, notice the dir command. Python's dir is like the dir command at a DOS prompt, but,
the Java(TM)
Class
Libraries:
A Tutorial
for or
Building
Web
unlike the DOS dirPython
, whichProgramming
lists files and with
directories,
it shows
members
of a module,
class,
instance.
This
and
Enterprise
Applications
with
Jython
covers
important
topics
such
as:
means that you can use it to list a comment's attributes.

>>> dir (comments)


Fundamental
programming'__name__',
concepts, including
statements, expressions,
['Camp', '__doc__',
'__file__',
'sayCampHello']

interpreters, and compilers


Here we see the __file__ and __name__ attributes, which provide the file path and name of this module.
Python basics, including
operators,
classes,
errors,
We also see Camp and sayCampHello
, so we can
check string
if theyformatting,
have the __namespaces,
doc__ attribute.
(Follow
and
exceptions
along.)
programming
concepts
>>> from commentsObject-oriented
import Camp,
sayCampHello
>>> dir (Camp) # List the attributes for Camp class
File input/output
['__doc__', '__module__', 'sayHello']
>>> dir (sayCampHello)
# List
attributes for sayCampHello
Python's intrinsic
functions
[]
>>> Camp.__doc__ Formatting, parsing, and manipulating strings
'Example showing a class document string'
Interfacing with the Java APIs and working with Java Streams
>>> sayCampHello.__doc__
'Example showing a function document string'
Using Python and Java Swing to create GUIs
TheCamp class does have a __doc__ attribute listing, but, strangely, the sayCampHello() function
Working
with SQL
and That's
JDBC(TM)
doesn't. Still, we can print out
its document
string.
because, although functions don't show attributes, they
do have the __doc__ attribute built in.
Python and Java applets

Statements In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
samples
thisa book
a useful learning
experience.
A statement is simplyand
annumerous
instructioncode
to Python
to make
perform
task. Through
the interpreter,
Python reads the
statement and does as instructed. In other words, it executes the statement. In this example, each line is a
Whether you are a sophisticated computer user new to programming or a serious
statement.
application developer, Python Programming with the Java(TM) Class Libraries will
give %s
you insight
into the
power
of Python and the know-how to put it to work.
Hello = "Hello
how are
you
doing"

from java import awt


print ("Hello World")

777

By default, a statement is contained on a single line. A multiline statement is indicated by a backslash at the end

of each of its lines and


an indentation
at the beginning
of the next.
Here's
one complete
statement
spanning two
Python
Programming
with the Java
Class
Libraries:
A Tutorial
for Building
lines:
Web and Enterprise Applications with Jython
By Richard Hightower

>>> reallyLongLine = 5 + 5 - 5 * 5 /5 * 100 - 1000 \


+ 200 - 300 + Publisher:
60 / 5Addison Wesley
Pub Date: June 28, 2002

Two statements can fit on one line if they're separated by a semicolon.

>>>

ISBN: 0-201-61616-5
Table of
Pages:
640
print("Hello"); print("Goodbye")
Contents

Hello
Goodbye

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
novices and
professionals
You can also end a statement
with
a semicolon.alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
>>> print ("This
statement
application
development.has a semicolon at the end");

This statement has a semicolon at the end


>>> print ("This
one begins
doeswith
not")
This tutorial
coverage of some of the basics of Python programming. Using
This one doesplenty
notof skill-building exercises and interactive programming sessions, this book will
>>>
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
Stylewise, an endingcapabilities
semicolon isn't
the bestthe
idea,
butthat
if you're
Jython
or CPython
and shows
ways
Pythonswitching
interfacesbetween
with Java
APIsand
forJava
professional
and C or C++, it's a nice
feature
because
in
these
languages
using
semicolons
to
terminate
a
line
is
standard. You
application development.
can't do this when switching between C++ and Visual Basic. If you try, you'll probably get a few frustrating
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
syntax errors.
and Enterprise Applications with Jython covers important topics such as:
Fundamental programming
concepts,
including statements,
expressions,
For Programmers:
Multiline
Statements
and
Visual
interpreters, and compilers
Basic
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
If you come from a Visual
Basic background, Python's style of line continuation should be familiar.
The only real difference between the two is Python's use of a backslash (\) and Visual Basic's use
programming
concepts End,Sub End, etc.) to mark the end
of an underscore(_)Object-oriented
and an End statement
(Function
of a statement instead of indentation.
File input/output
If you come from a Java background, Python's line continuation and code block indentation may
Python's intrinsic functions
seem a little weird. Java explicitly ends statements with a semicolon, so there's no need for a line
continuation indicator.
It uses the
backslash
string continuation.
Formatting,
parsing,
andfor
manipulating
strings Indenting in Java is strictly up
to the taste and style of the individual programmer.
Interfacing with the Java APIs and working with Java Streams
Statements use whitespacetabs and spacesto denote an associated block of code. It can also denote a suite
Pythonstatement.
and Java Swing
to create
GUIs and suites will be covered in Chapter
associated with a clause in Using
a compound
(Compound
statements
3.) The amount of whitespace within a statement doesn't matter. All of the following examples do the same thing
Working with SQL and JDBC(TM)
even though the whitespace in each is different.

x=1
x = 1
x =
1
x =
1

Python and Java applets


In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.

ExpressionsWhether you are a sophisticated computer user new to programming or a serious

application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.
Expressions are also instructions to Python to perform a task. That task is to return a value, such as the result of a
mathematical operation or the truth or falsity of a statement. Expressions can be assigned variables. Also, many
of them use operators, which can be words like and,or, and not, or symbols such as + (plus), - (minus), *
(multiplication), and = (equals). We'll cover operators in detail in Chapter 3. For now, just remember that

777

expressions return a Python


value and
usually use operators.
Programming
with the Java

Class Libraries: A Tutorial for Building


Web and Enterprise Applications with Jython
By Richard Hightower

For Publisher:
Novices:
in Spreadsheets
AddisonExpressions
Wesley
Pub Date: June 28, 2002

If you've ever used spreadsheets,


you've used expressions and operators. An expression is
ISBN: 0-201-61616-5
Table
of
equivalent
to a spreadsheet
formula.
Pages: 640
Contents

Let's say that, in cell D1 of a spreadsheet, you have the formula =(A1*B1)/C1, which
Characterized by ease of use, richness of expression, and concise syntax, Python has
multiplies cell A1 by cell B1 and then divides their product by C1. The equivalent in Python is D1
remained a premier programming language for more than a decade, and is used by
= (A1*B1)/C1
, where D1,A1, and C1 are variables. The right side of this
novices and professionals alike. In particular, its close relationship to Java(TM) makes
equation(A1*B1)/C1is the actual expression.
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
To illustrate how expressions work, we'll first create three variables, x,y, and z.
This tutorial begins with coverage of some of the basics of Python programming. Using
>>> x,y,z = 1,
2,of 3
# This exercises
is *not*
an expression
plenty
skill-building
and interactive
programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
(Notice the commenttechniques.
in the above
example.
See the
box titled "Assignment"
for an explanation.)
For
experienced
programmers,
the book demonstrates
Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
The following examples are pretty self-explanatory. They illustrate, in turn, the use of the multiplication operator,
application development.
the division operator, and the logical operator and (all of which will be covered in Chapter 3). What they all
demonstrate is this simple
Expressions
return
values.A Tutorial for Building Web
Pythonpoint:
Programming
withare
thestatements
Java(TM)that
Class
Libraries:

>>> y * 2
4
>>> 10 / z
3
>>> x and y
2

and Enterprise Applications with Jython covers important topics such as:
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
Object-oriented programming concepts

>>> x and 0
0

File input/output
Python's intrinsic functions

Assignment
Formatting, parsing,
and manipulating strings
with the Java
APIsinand
withthe
Java
Streamsstated This
In the example that Interfacing
creates the variables
we used
ourworking
expression,
comment
is *not* an expression. In fact, it may look like an expression, but in Python it's
Using
Python
andat Java
Swing to code,
createinGUIs
actually an assignment.
Take
a look
the following
which it appears that a value is
returned:
Working with SQL and JDBC(TM)

x = y = z = 3

Python and Java applets

In addition, the book contains instructions for downloading and installing the Python
We might think that z = 3 returns 3, and y = z returns the value of z, which is 3, but this isn't
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
the case. We know this because in interactive interpreter mode an expression is printed out to the
and numerous code samples make this book a useful learning experience.
screen.
Whether you are a sophisticated computer user new to programming or a serious

>>> x = y = z = 3
application developer, Python Programming with the Java(TM) Class Libraries will
>>> x = z
give you insight into the power of Python and the know-how to put it to work.
>>> x==z
1

777

As you can see, x = z and x = y = z = 3 aren't printed to the screen, which means that

they don't return


a value
and so are notwith
expressions.
In Python,
the use ofAthe
comparison
operator
Python
Programming
the Java
Class Libraries:
Tutorial
for Building
(==), not the Web
assignment
operator, isApplications
what makes awith
statement
an expression. This is because the
and Enterprise
Jython
== returns a value,
usually
1 or 0, whereas = doesn't.
By Richard
Hightower
In Java, C, and C++,
an assignment
is an expression, which is why confusing the assignment and
Publisher:
Addison Wesley
comparison operators
is a common programmer error (mostly in C and C++; Java has its own way
Pub Date: June 28, 2002
of dealing with this problem).

Table of
Consider
Contents

ISBN: 0-201-61616-5

Pages: 640

these two examples:

by ease of use, richness of expression, and concise syntax, Python has


if(x=z): Characterized
pass
remained
a
premier
programming language for more than a decade, and is used by
while(x=z): pass
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
Here the if and
whiledevelopment.
statements expect an expression, that is, a value to be returned, but the
application
assignment operator can't do this, and syntax errors are the result.
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
Variables help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
and shows
the waysthat
that
Python
interfaces
Java
for professional
Think of variables ascapabilities
individual storage
containers
hold
different
kinds with
of data
in APIs
memory.
Each variable has
development.
a name and a value, application
and each variable
value has a type.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web

Declaring Variables
and Enterprise Applications with Jython covers important topics such as:

In most languages, before you can use a variable you have to declare it; that is, you must assign it a name and a
Fundamental
statements,
type. Python is different; unlike
in other programming
languages, youconcepts,
declare aincluding
variable implicitly
byexpressions,
assigning a value to it.
interpreters, and compilers
Here's an example:

basics,
including
operators,
string
classes, errors,
# declare age to Python
be of
type
integer
and
offormatting,
value namespaces,
28.
and
exceptions
age = 28
programming
# declare name toObject-oriented
be of type
stringconcepts
# and of value "rick"
File input/output
name = "rick"
Python's intrinsic functions
Variable declarations can go anywhere in a module. You can declare more than one variable at once by stringing
them together. (Follow along).
Formatting, parsing, and manipulating strings

>>> x,y,z = 1,2,3Interfacing with the Java APIs and working with Java Streams
>>> print ("x=" + `x` + " y=" + `y` + " z=" +`z`)
x=1 y=2 z=3
Using Python and Java Swing to create GUIs
The first statement defines Working
three variables
as ofand
typeJDBC(TM)
Integer (that is, whole numbers) and assigns them the
with SQL
values1,2, and 3, such that x = 1,y = 2, and z = 3. Notice that in the second statement the variable
Java
applets
names are enclosed in backPython
quotes.and
That
tells
Python to convert the variable to a string.

addition,
bookstringing
containstogether
instructions
for variable
downloading
and installing
the Python
Here's an interactiveIn
example
of the
Python
several
definitions
with different
types:
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
>>> name, age,
sex = "Kiley",
22, this
"female"
and numerous
code samples make
book a useful learning experience.

>>> print (name + " is " + `age` + " and " + sex)
Whether
you are a sophisticated computer user new to programming or a serious
Kiley is 22 and
female
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

For Programmers: Variable Declarations in Python


asPublisher:
Compared
to Visual Basic and Java
Addison Wesley
Pub Date: June 28, 2002

In Python, you can't access a variable that you haven't declared, but remember: The first time you
ISBN: 0-201-61616-5
Table
assignofa value to a variable, you declare that variable. That means that you can't make the mistake
Pages: 640
Contents
of trying to use an unassigned variable, as you can in Visual Basic. Only if you don't use Visual's
Explicit option can you use a variable that has no value assigned.
Characterized by ease of use, richness of expression, and concise syntax, Python has
remained
a premier
programming
language
forPython
more than
a decade,
is used
Visual Basic has
a Variant
type,
which can be
anything.
variables
don'tand
have
a typebyunto
novices
and
professionals
alike.
In
particular,
its
close
relationship
to
Java(TM)
makes
themselves but are whatever type is assigned to themString,List, and so forthso they
the
two
languages,
when
used
in
combination,
ideal
for
Web
and
distributed
enterprise
support dynamic polymorphism with their late-binding features. Visual Basic also supports
applicationasdevelopment.
dynamic polymorphism
well. (Polymorphism is discussed in Chapter 6.)

Thisdeclaration
tutorial begins
with
coverage
of some
of the basics
of Python
programming.
Using
In Java, variable
is very
strict.
You have
to explicitly
declare
the variables
themselves
plenty
of
skill-building
exercises
and
interactive
programming
sessions,
this
book
will
and their types. Even so, you can do dynamic polymorphic programming if you declare a variable
a
help
those
new
to
programming
develop
an
understanding
of
concepts
and
practical
superclass of the instance you're working with.
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities
showsand
thedynamic
ways thatthan
Python
forcome
professional
Obviously, Python
is moreand
flexible
Java,interfaces
but not aswith
typeJava
safe.APIs
If you
from a
applicationthis
development.
Smalltalk background,
is probably a boon, but probably not if you come from C++. Read
Appendix C on the advantages of scripting languages, and then decide for yourself.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

Valid Variable Names


Fundamental programming concepts, including statements, expressions,
Variable names in Python can start with a letter or an underscore (_). After the first character, they can also
interpreters, and compilers
contain numbers, and they can be as long as you want them to be. Keep in mind that variable names are case
sensitive. That is, age,AGE
, and Age
mean
different
things tostring
the interpreter.
are a fewclasses,
valid variable
Python
basics,
including
operators,
formatting,Here
namespaces,
errors,
names:
and exceptions

_name = "John Souza"


Object-oriented programming concepts
favorite_sport = "Baseball"
SF49ers = "San Francisco
49ers"
File input/output
Here are some invalid ones:Python's intrinsic functions

$name = "John Souza"


Formatting, parsing, and manipulating strings
favorite sport = "Baseball"
Interfacing 49ers"
with the Java APIs and working with Java Streams
49ers = "San Francisco

Data Types

Using Python and Java Swing to create GUIs

Working with SQL and JDBC(TM)


Each variable has a type, which can be the following:
Python and Java applets
addition,
the book
instructions for downloading and installing the Python
One of the sixIn
basic
data types
(see contains
the next section)
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
One of the fiveand
standard
container
types make this book a useful learning experience.
numerous
code samples
One of the standard
callable
types
Whether
you are
a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
One of the twogive
object-oriented
types
you insight into
the power of Python and the know-how to put it to work.
Any Java class or standard object

777

In this chapter we'll cover the basic types.

The Basic Data


Types
Python
Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

Most of the six basic data types in Python are analogous to the basic types in Visual Basic and Java. Here they
are:
Publisher: Addison Wesley
Pub Date: June 28, 2002

String sequences
of characters
ISBN:
0-201-61616-5

Table of
Pages: 640
Contents
Integer integers (whole numbers)

Characterized
by ease of use, richness of expression, and concise syntax, Python has
Float floating-point
numbers

remained a premier programming language for more than a decade, and is used by
Long largenovices
integersand professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
None no value
application development.

Type type This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
All of them are builthelp
into those
the system.
in Java, everything
Python is an of
object,
including
functions,
new toUnlike
programming
develop an in
understanding
concepts
and practical
modules, and types. techniques.
(We'll get toFor
objects
in Chapter
6, which is the
on object-oriented
programming.)
experienced
programmers,
book demonstrates
Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
Float,Integer,application
and Longdevelopment.
are numeric types. The table below shows their individual rangesthat is, the
size of the values they can hold.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
Type
FromApplications with Jython covers
Toimportant topics such as:
and Enterprise
Integer
2,147,483,648
2,147,483,647

Float
Long

4.9e324
1.7976931348623157e308
Fundamental programming concepts, including statements, expressions,
As smalland
as you
want
As big as you want
interpreters,
compilers

Python basics, including operators, string formatting, namespaces, classes, errors,


and exceptions
Object-oriented programming concepts

For Programmers:
Numeric Type Ranges
File input/output
The range of the numericPython's
types depends
onfunctions
the system running them, unless, of course, they're running under
intrinsic
Java. This means that, in Jython, Integer is implemented with Java Int, and Float is implemented
with Java Double. The Formatting,
reverse is true
in CPython:
Integerstrings
is implemented with C Long, and Float
parsing,
and manipulating
with C Double.Long has an unlimited range in both CPython and Jython. Unlike in C, in Java Integer
Interfacing
with the Java APIs and working with Java Streams
always holds the same range
of values.

Using
Python
and JavaInteger
Swing to create
GUIs type, but trying to remember this
You often need to know the
biggest
or smallest
or Float
information is difficult. I'm going to show you an interactive session that will give you this information when
Working
with
SQL and
JDBC(TM)
you need it. Remember that
Float
in Python
equates
to Java Double, so the first thing to do is import
class Double from the java.lang package.
Python and Java applets

>>> from java.lang import Double

In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
anda dir
numerous
code samples
this book a useful
learning experience.
We could instead do
on Double
to seemake
its MAX_VALUE
and MIN_VALUE
attributes.
Whether you are a sophisticated computer user new to programming or a serious
>>> dir (Double)
application
developer, Python
Programming with the Java(TM)
Class Libraries will
['MAX_VALUE',
'MIN_VALUE',
'NEGATIVE_INFINITY',
'NaN',
give
you
insight
into
the
power
of
Python
and
the
know-how
to
put
it to work.
'POSITIVE_INFINITY', 'TYPE', '__doc__', '__init__', '__module__',
'compareTo', 'doubleToLongBits', 'infinite', 'isInfinite', 'isNaN',
'longBitsToDouble', 'naN', 'parseDouble', 'toString', 'valueOf']

777

Here's how to access


the largest
and smallest
Float
, respectively:
Python
Programming
with
the Java
Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython

>>> Double.MAX_VALUE
By Richard Hightower
1.7976931348623157E308
Publisher: Addison Wesley

>>> Double.MIN_VALUE
Pub Date: June 28, 2002
4.9E-324

Table of
Contents

ISBN: 0-201-61616-5

Pages: 640

Now we'll do the same thing for the biggest and smallest Integer.
Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier
programming
>>> from java.lang
import
Integerlanguage for more than a decade, and is used by
novices
and
professionals
>>> max = Integer.MAX_VALUE alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
>>> min = Integer.MIN_VALUE
>>> max, minapplication development.

(2147483647, -2147483648)

This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
TypeType
capabilities and shows the ways that Python interfaces with Java APIs for professional
application
development.
As I said before, everything
in Python
is an object, that is, a "container" for properties and methods. This means
that all of the basic types are of type Typethat is, a variable type that holds another variable type. Here's the
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
proof:
and Enterprise Applications with Jython covers important topics such as:

>>> if type(FloatType) == TypeType:


...
print("FloatType is of TypeType")
Fundamental programming concepts, including statements, expressions,
...
interpreters, and compilers
FloatType is of TypeType
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions

For Programmers: Jython versus Python

Object-oriented programming concepts


In Jython, the built-in type() function returns the class name of the Java implementation for that
input/output
type for Jython. For File
example:
functions
>>> int = 1 Python's
#holdsintrinsic
a integer
>>> float = 1.0 #holds a float
Formatting, parsing, and manipulating strings
>>> long = 1L #holds a long
>>> string =Interfacing
"string"
a and
string
with #holds
the Java APIs
working with Java Streams
>>> type (int)
<jclass org.python.core.PyInteger
at GUIs
-712990957>
Using Python and Java Swing to create
>>> type (long)
<jclass org.python.core.PyLong
at 46702445>
Working with SQL and JDBC(TM)
>>> type (string)
Python and Java applets
<jclass org.python.core.PyString
at -710631661>
>>> type (float)
In addition, the book contains instructions
downloading and installing the Python
<jclass org.python.core.PyFloat
at for
-1307009172>
language
and
the
Java
Development
Kit
(JDK).
Terminology, definitions, explanations,
>>> type (FloatType)
and
numerous
code
samples
make
this
book
a
useful
learning experience.
<jclass org.python.core.PyJavaClass at -693854445>
>>> type (TypeType)
Whether you are a sophisticated computer user new to programming or a serious
<jclass org.python.core.PyJavaClass at -693854445>
application developer, Python Programming with the Java(TM) Class Libraries will
>>> type (None)
give you insight into the power of Python and the know-how to put it to work.
<jclass org.python.core.PyNone at -693592301>

777

In Python, the type() function returns Int,Long,String, and Float instead of the Java
class name.

None

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

Variables that reference nothing are of type None, meaning that they have no value. If you work with databases,
Publisher: Addison Wesley
think of None as similar to NULL. Don't think of it as zero, which is a value. Programmers, you may know that
Pub Date: June 28, 2002
in Java and Visual Basic the counterparts to Python's None are, respectively, null and Nothing. In Delphi,
ISBN: 0-201-61616-5
this same
concept
is called Nil
.
Table
of

Contents

Pages: 640

Python Collection
Types
Characterized
by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
novicesapart
and from
professionals
alike.
In particular,
its closecollection
relationship
to Java(TM)
makes
One thing that sets Python
most other
languages
is its built-in
types.
As in the real
world, in
the
two
languages,
when
used
in
combination,
ideal
for
Web
and
distributed
enterprise
programming a collection represents more than one item. By "built-in" I mean that Python uses a special syntax
application
for its collections, which
it calls development.
sequences. Strings are also considered sequences in Python, so all of the rules
that apply to strings also apply to collectionsslice notation, indexes, and so forth.
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
For experienced programmers,
the book demonstrates
Python's
Fortechniques.
Programmers:
Hashtables,
Vectors,
andbreadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
Collection Objects
application development.
Python
Programming
with the Java(TM)
Class
Libraries:
A Tutorial
Building
Web
If you use Java,
you probably
use hashtables
and vectors
in about
85 percent
of thefor
programs
you
and
Enterprise
Applications
with
Jython
covers
important
topics
such
as:
write. Hashtables are similar to Python dictionaries, and vectors are similar to Python lists. The key
difference is that Python's lists, dictionaries, and tuples have built-in syntax support for addition,
multiplication, member referencing, literals, for loop iteration, and so forth. This makes things
Fundamental programming concepts, including statements, expressions,
easier on the programmer. It also means that you can define objects to act like collections so that
interpreters, and compilers
other programmers can use the syntax when working with them.
Python basics, including operators, string formatting, namespaces, classes, errors,
The Visual Basic collection object is like Python's list and dictionary rolled into one. Visual Basic
and exceptions
supports for loop iteration, as Python does, but otherwise it offers no collection support. Perl's
collection support isObject-oriented
the only one that
comes closeconcepts
to Python's.
programming

Lists

File input/output

Python's intrinsic functions


Whereas a string holds a sequence of characters, a list holds a sequence of objects of various types, which you
parsing,
and manipulating
stringswhich we learned about in Chapter 1.
access as you do charactersFormatting,
in strings. You
can even
use slice notation,

>>>
#Define a Interfacing
list with
5 Java
values
inworking
it with Java Streams
with the
APIs and
>>> mylist = ["hello","goodbye", 1, 1.0, 50000000000000000L]
Pythonobject
and Java Swing
to create
GUIs
>>>
#print theUsing
first
in the
list
>>> print (mylist[0])
Working with SQL and JDBC(TM)
hello
>>>
#print the first two objects in the list
Python and Java applets
>>> print (mylist[0:2])
['hello', 'goodbye']
In addition, the book contains instructions for downloading and installing the Python
>>>
#printlanguage
the whole
list
and the Java
Development Kit (JDK). Terminology, definitions, explanations,
>>> print (mylist[0:])
and numerous code samples make this book a useful learning experience.
['hello', 'goodbye', 1, 1.0, 50000000000000000L]
>>>
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
You can tell a list bygive
the square
brackets
[ power
]) thatof
surround
brackets mean
are no items in
you insight
into (the
Python it.
andEmpty
the know-how
to putthat
it tothere
work.
the list.

777

Lists can be added and multiplied.

>>> list1 = [] #create an empty list

>>> list2 = ["a",


"b", 10, 11,
12,Java
13]Class Libraries: A Tutorial for Building
Python Programming
with the
>>> list1 # show
the
emptyApplications
lists contents
Web and
Enterprise
with Jython
[]
By Richard Hightower
>>> list2 #showPublisher:
the contents
of the list with items
Addison Wesley
['a', 'b', 10, Pub
11,
12,
13]
Date: June 28, 2002
ISBN: 0-201-61616-5

of = list2 + list2 #add the lists together


>>> Table
list1
Pages: 640
>>> Contents
list1
['a', 'b', 10,
11, 12,by ease
13,of'a',
'b',of10,
11, and
12,concise
13] syntax, Python has
Characterized
use, richness
expression,

remained a premier programming language for more than a decade, and is used by

>>> list1 = list2


* professionals
2 #multiply
a particular,
list its close relationship to Java(TM) makes
novices and
alike. In
>>> list1
the two languages, when used in combination, ideal for Web and distributed enterprise
['a', 'b', 10,
11, 12,
13, 'a', 'b', 10, 11, 12, 13]
application
development.
You can also appendThis
and tutorial
removebegins
list items,
the listofobject's
remove()
methods.
withwith
coverage
some ofappend()
the basics ofand
Python
programming.
Using
Chapter 5 is where we'll
cover
methods
and
functions;
for
now
all
you
need
to
know
to
use
append()
plenty of skill-building exercises and interactive programming sessions, this book willand
remove() is the form
. (You'll and
learnpractical
about
help variable_name.methodname(arguments)
those new to programming develop an understanding of concepts
arguments in Chaptertechniques.
5 as well.)For
Here's
an example
that continues
previous
interactive
session:
experienced
programmers,
thethe
book
demonstrates
Python's
breadth of

capabilities and shows the ways that Python interfaces with Java APIs for professional

>>> # remove 'a' from the list


application development.
>>> list1.remove('a')
>>> # displayPython
theProgramming
contentswith
ofthelist1
Java(TM) Class Libraries: A Tutorial for Building Web
>>> list1
and Enterprise Applications with Jython covers important topics such as:
['b', 10, 11, 12, 13, 'a', 'b', 10, 11, 12, 13]
concepts, including statements, expressions,
>>> # remove 'a' Fundamental
from theprogramming
list again
interpreters, and compilers
>>> list1.remove('a')
>>> #display the contents of the list
Python basics, including operators, string formatting, namespaces, classes, errors,
>>> list1
exceptions
['b', 10, 11, 12,and13,
'b', 10, 11, 12, 13]
programming
>>> #put the 'a' Object-oriented
back in the
list concepts
>>> list1.append('a')
File input/output
>>> list1
['b', 10, 11, 12,Python's
13, intrinsic
'b', functions
10, 11, 12, 13, 'a']

>>> len (list1) Formatting, parsing, and manipulating strings


11
Interfacing with the Java APIs and working with Java Streams
Note that remove() gets rid of only the first occurrence of an item, so to remove both instances of 'a', we
Using Python andtwice.
Java Swing
create
have to invoke list1.remove('a')
By the to
way,
youGUIs
can determine how many items are in a list
with the len() (length) function.
Working with SQL and JDBC(TM)
Another interesting thing you can do with lists is sort them, with sort(), and reverse their order, with
Python
Java
applets
reverse(). For instance,
youand
might
want
your list in alphabetical or reverse alphabetical order.
In addition, the book contains instructions for downloading and installing the Python
>>> names = []
the Java
Development
(JDK). Terminology,
definitions, explanations,
>>> #append alanguage
bunchandof
names
to theKitnames
list
and
numerous
code
samples
make
this
book
a
useful
learning
experience.
>>> names.append("Kiley")
>>> names.append("Rick")
Whether you are a sophisticated computer user new to programming or a serious
>>> names.append("Mary")
application developer, Python Programming with the Java(TM) Class Libraries will
>>> names.append("Adam")
give you insight into the power of Python and the know-how to put it to work.
>>> names.append("Missy")
>>> names.append("Martha")
>>> #display names before the sort
>>> names
['Kiley', 'Rick', 'Mary', 'Adam', 'Missy', 'Martha']

777

Python Programming with the Java Class Libraries: A Tutorial for Building

>>> #sort theWeb


names
alphabetically
and Enterprise
Applications with Jython
>>> names.sort()
By Richard Hightower
>>> #display names after sort
>>> names
Publisher: Addison Wesley
['Adam', 'Kiley',
'Martha',
'Mary', 'Missy', 'Rick']
Pub Date:
June 28, 2002
ISBN: 0-201-61616-5

of
>>> Table
#reverse
the Pages:
order
of the list
640
>>> Contents
names.reverse()
>>> names
Characterized by ease of use, richness of expression, and concise syntax, Python has
['Rick', 'Missy',
'Martha',
'Kiley',
'Adam']
remained'Mary',
a premier programming
language
for more than
a decade, and is used by

novices and professionals alike. In particular, its close relationship to Java(TM) makes
Withinsert() you can insert items into the middle of a list. With index(), you determine where an item
the two languages, when used in combination, ideal for Web and distributed enterprise
is numerically.
application development.

>>> #display the contents of the names list


This tutorial begins with coverage of some of the basics of Python programming. Using
>>> names
plenty of skill-building exercises and interactive programming sessions, this book will
['Rick', 'Missy', 'Mary', 'Martha', 'Kiley', 'Adam']
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
>>> #determine the index of the "Rick" string
capabilities and shows the ways that Python interfaces with Java APIs for professional
>>> names.index("Rick")
application development.

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web

>>> #insert "Kiley"


string
next
"Rick"
and Enterprise
Applications
withto
Jython
covers important topics such as:
>>> names.insert(1, "Kiley")
>>> names
programming
including'Kiley',
statements, expressions,
['Rick', 'Kiley',Fundamental
'Missy',
'Mary',concepts,
'Martha',
'Adam']
interpreters, and compilers

>>> #find the index of the "Martha" string


Python basics, including operators, string formatting, namespaces, classes, errors,
>>> names.index("Martha")
and exceptions
4
Object-orientedstring
programming
concepts
>>> #insert the "Miguel"
next
to Martha
>>> names.insert(5,
"Miguel")
File input/output
>>> #display the name list
>>> names
Python's intrinsic functions
['Rick', 'Kiley', 'Missy', 'Mary', 'Martha', 'Miguel', 'Kiley', 'Adam']
Formatting, parsing, and manipulating strings

count() determines the number of times an item occurs in a list.


Interfacing with the Java APIs and working with Java Streams

>>>
>>>
>>>
>>>
3

# Initialize the names list


names = ["James",
"James",
"James",
"Joe", "Sam"]
Using Python
and Java Swing
to create"Bob",
GUIs
# Count number of "James" strings in names
Working with SQL and JDBC(TM)
names.count("James")
Python and Java applets

Tuples

In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
Tuples are collectionand
types
similar to
listssamples
in that they
items.
However,
they're
immutable, which means
numerous
code
makecontain
this book
a useful
learning
experience.
that you can't change them once definedyou can't append or remove items or add two tuples together. All you
Whether you are a sophisticated computer user new to programming or a serious
can do is multiply them.
application developer, Python Programming with the Java(TM) Class Libraries will
>>> # create give
an you
empty
insighttuple
into the power of Python and the know-how to put it to work.

>>>
>>>
>>>
>>>

tuple1 = ()
# create a tuple with three greetings
tuple2 = ("Hi", "Bye", "Salutations")
# multiply this tuple2 and assign to tuple

777

>>> tuple1 = Python


tuple2
* 2
Programming
with the Java Class Libraries: A Tutorial for Building
>>> # displayWeb
the
of tuplewith Jython
andcontents
Enterprise Applications
>>> tuple1 ByRichard Hightower
('Hi', 'Bye', 'Salutations', 'Hi', 'Bye', 'Salutations')
Publisher: Addison Wesley

This example shows tuples


being declared in parentheses, but this isn't mandatory. Furthermore, you can use a
Pub Date: June 28, 2002
tuple to initialize more than one variable and use more than one variable to initialize a tuple. To see this, follow
ISBN: 0-201-61616-5
Table
of interactive session.
along
with this

Contents

>>>
>>>
>>>
(3,

Pages: 640

#initialize a tuple without parentheses


by ease of use, richness of expression, and concise syntax, Python has
tuple3 = Characterized
3,2,1
remained
a
premier
programming language for more than a decade, and is used by
tuple3
novices
and
professionals
alike. In particular, its close relationship to Java(TM) makes
2, 1)

the two languages, when used in combination, ideal for Web and distributed enterprise
application
development.
Here we initialized tuple3
with
three numbers without parentheses. To be explicit, we defined a variable of
typeTuple that contains three numeric items with values of 3,2, and 1.
This tutorial begins with coverage of some of the basics of Python programming. Using
plentywe
of skill-building
this
book
will
In the following example,
initialize threeexercises
numbersand
withinteractive
a tuple. Inprogramming
other words, sessions,
we declare
three
variables
help
those
new
to
programming
develop
an
understanding
of
concepts
and
practical
namedx,y, and z; then we assign 3 to x,2 to y, and 1 to z.
techniques. For experienced programmers, the book demonstrates Python's breadth of
>>> x,y,z = 3,2,1
capabilities and shows the ways that Python interfaces with Java APIs for professional
>>> x
application development.

3
>>> y
2
>>> z
1

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

Fundamental programming concepts, including statements, expressions,


interpreters,
compilers
Now we can use these three
variables toand
create
a tuple. That is, we use them to declare a tuple, tuple4, that
contains the three variables' values.
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
>>> tuple4 = x,y,z

>>> tuple4
(3, 2, 1)

Object-oriented programming concepts

File input/output
The opposite of this is to use a tuple to declare three new variables by defining them and using tuple4 to
initialize them.
Python's intrinsic functions

>>>
>>>
3
>>>
2
>>>
1

q,r,s = tuple4
Formatting, parsing, and manipulating strings
q
Interfacing with the Java APIs and working with Java Streams

r
Using Python and Java Swing to create GUIs

s
Working with SQL and JDBC(TM)
Python and Java applets
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

For Novices: Lists and Tuples Are Both Sequences


Publisher:
Addison Wesley
Lists work as tuples
do for declaring
multiple variables and for using variables to assign values to
Pub Date:
28, 2002
lists. The only difference
is June
that they
require brackets. The following example is similar to the
examples we saw forISBN:
tuples,0-201-61616-5
but it uses lists instead.

Table of
Contents

>>>
>>>
5
>>>
6
>>>
7
>>>
>>>
[5,
>>>
>>>
5
>>>
6
>>>
7

Pages: 640

x,y,z = [5,6,7]
x
Characterized by ease of use, richness of expression, and concise syntax, Python has
y
z

remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.

list1
= tutorial
[x,y,z]
This
begins with coverage of some of the basics of Python programming. Using
list1
plenty of skill-building exercises and interactive programming sessions, this book will
6, 7]
help those new to programming develop an understanding of concepts and practical
q,r,s
= list1
techniques.
For experienced programmers, the book demonstrates Python's breadth of
q
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.

r
s

Dictionaries

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers

Python basics, including operators, string formatting, namespaces, classes, errors,


A dictionary, another Python collection type, stores keys and values. It uses key/value pairs to locate a value,
and exceptions
which can be any object of any type. The dictionary declares a series of key/value pairs using the notation
key:value and separates
the individualprogramming
pairs with commas.
Object-oriented
concepts

>>>
>>>
>>>
Joe
>>>

namesToAges =File{"joe":30,
"kelly":32, "john":28}
input/output
joesAge = namesToAges["joe"]
print ("Joe is
" +intrinsic
`joesAge`
Python's
functions + " years old")
is 30 years old
Formatting, parsing, and manipulating strings

namesToAges is the dictionary,


"joe"
is the
andand
30working
is the value.
Interfacing
with the
Javakey,
APIs
with Java Streams
Python and
to create
Remember that a dictionaryUsing
is a sequence,
andJava
likeSwing
a sequence
youGUIs
access it by its name and by the index of the
value in it that you're looking for. What's different is that the location is a key into the dictionary. In the last
with
andwe
JDBC(TM)
example, we wanted to findWorking
Joe's age.
ToSQL
do that
had to use the key, "joe", in square brackets like a list, in
thenamesToAges dictionary. Keys can be any object of any immutable type, such as strings, tuples, or
applets
numeric values. However, Python
you canand
useJava
tuples
for dictionary keys only if they contain only immutable items.
In addition,
bookits
contains
for downloading
installing
the Python
A dictionary can be searched
by the
its keys,
values,instructions
or its key/value
pairs. To getand
all of
a dictionary's
keys, values,
language
and
the
Java
Development
Kit
(JDK).
Terminology,
definitions,
explanations,
or pairs, you use keys(),values() , or items(), respectively. We'll continue the previous
example to
and numerous code samples make this book a useful learning experience.
illustrate how.
Whether
you arenamesToAges
a sophisticated computer
user new to programming or a serious
>>>
#display
dictionary
application
developer,
Python
Programming
with the Java(TM) Class Libraries will
>>> namesToAges
give
you
insight
into
the
power
of
Python
and
the know-how to put it to work.
{'john': 28, 'joe': 30, 'kelly': 32}

777

>>>
#display keys in dictionary
>>> namesToAges.keys()
['john', 'joe', 'kelly']

Python Programming with the Java Class Libraries: A Tutorial for Building

>>>
#display
values
in dictionary
Web
and Enterprise
Applications
with Jython
>>> namesToAges.values()
By Richard Hightower
[28, 30, 32]
Publisher: Addison Wesley

>>>
#display
items in dictionary
Pub Date: June 28, 2002
>>> namesToAges.items()
ISBN: 0-201-61616-5
Table of 28), ('joe', 30), ('kelly', 32)]
[('john',

Pages: 640

Contents

To see if a particular key, such as "joe" or "james" is in a dictionary, we can do this:


Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
>>> namesToAges.has_key("joe")
novices and professionals alike. In particular, its close relationship to Java(TM) makes
1
the two languages, when used in combination, ideal for Web and distributed enterprise
>>> namesToAges.has_key("james")
application development.
0

This tutorial begins with coverage of some of the basics of Python programming. Using

Advanced Topic:
Determining
at Runtime
plenty of skill-building
exercisesTypes
and interactive
programming sessions, this book will

help those new to programming develop an understanding of concepts and practical


For experienced
programmers,
book demonstrates
breadth
of
You can determine atechniques.
type at runtime
with the built-in
type() the
function
along with thePython's
Python types
module,
capabilities
and
shows
the
ways
that
Python
interfaces
with
Java
APIs
for
professional
which defines all of the basic types.
application development.
First, we import the types module and create some variables from all of the basic types.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
>>> from types
import Applications
*
and Enterprise
with Jython covers important topics such as:

>>>
>>>
>>>
>>>

int = 1 #holds a integer


float = 1.0 #holds a float
Fundamental
programming concepts, including statements, expressions,
long = 1L #holds
a long
interpreters,
and compilers
string = "string"
#holds
a string

Python string
basics,isincluding
operators,
string
formatting,
classes,
errors,
Now we test to see if the variable
of type String
. Here
we'll
be usingnamespaces,
the if statement,
which
works
and
exceptions
like if in other languages. Just remember that if's subordinate statements must be indented. (We'll be covering
this in Chapter 4.)
Object-oriented programming concepts
The... prompt tells you to enter the subordinate statement, print. Make sure to indent print, and then hit
File input/output
Enter to indicate that the if statement is finished.

Python's intrinsic functions


Here is your first if statement, step by step.
1. At the >>>, type

Formatting, parsing, and manipulating strings


Interfacing with the Java APIs and working with Java Streams

>>> if type(string) == StringType: [hit Return]


2. At the ... prompt, Using Python and Java Swing to create GUIs

[hit Tab] print ("string


StringType")
[hit Return]
Working withis
SQLaand
JDBC(TM)
3. At the ... prompt,
Python and Java applets
[hit Return]
In addition, the book contains instructions for downloading and installing the Python
The next three interactive
sessions
testJava
whether
the variable
is of
type Integer
, the variable
float is
language
and the
Development
Kitint
(JDK).
Terminology,
definitions,
explanations,
of type Float, andand
the numerous
variable long
is
of
type
Long
.
code samples make this book a useful learning experience.

>>> if type(int)
Whether==
youIntType:
are a sophisticated computer user new to programming or a serious
...
print("int
a IntType")
applicationis
developer,
Python Programming with the Java(TM) Class Libraries will
...
give you insight into the power of Python and the know-how to put it to work.
int is a IntType

777

>>> if type(float) == FloatType:


...
print("float is a FloatType")

...
Python Programming with the Java Class Libraries: A Tutorial for Building
float is a FloatType
Web and Enterprise Applications with Jython
By Richard Hightower

>>> if type(long) == LongType:


...
print("long
a Long")
Publisher:is
Addison
Wesley
...
Pub Date: June 28, 2002
long is a Long
ISBN: 0-201-61616-5

Table of

Pages: 640

Contents
Just for
a sanity check, let's see if the string variable is a Float type.

Characterized
of use, richness of expression, and concise syntax, Python has
>>> if type(string)
==by ease
FloatType:
remained
a
premier
programming
...
print("string is a float")language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
... else:
the two languages,
when
used in combination, ideal for Web and distributed enterprise
...
print("Don't
be a
GOOF!")
application
development.
...
Don't be a GOOF!

This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
Literals
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities
and shows
thewe
ways
thatcall
Python
APIs for professional
We've been using literals
since Chapter
1, but
didn't
theminterfaces
that. The with
term Java
is computerspeak
for a constant
application
development.
value; that is, what you
type is literally
what you get. In the following interactive session, for example, the
literals are "Hello World",100,3200000000000L, and 3.5.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise=Applications
Jython covers important topics such as:
>>> a_literal_string
"Hello with
World"

>>> a_literal_integer = 100


>>> a_literal_long
= 3200000000000L
Fundamental programming concepts, including statements, expressions,
>>> a_float_literal
= 3.5
interpreters, and compilers
Literals can be contained inPython
statements.
basics, including operators, string formatting, namespaces, classes, errors,

and exceptions
print ("Hello I am
a literal string")
Object-oriented programming concepts
Table 2-1. Escape Sequence Characters
File input/output
Character Meaning
Python's intrinsic functions
\\
Backslash

\'
\"
\a
\b
\f
\n
\r
\t
\v
\ooo
\xhh...

Single quoteFormatting, parsing, and manipulating strings


Double quote
Interfacing with the Java APIs and working with Java Streams
ASCII Bell (BEL)
ASCII Backspace
Using (BS)
Python and Java Swing to create GUIs
ASCII Formfeed (FF)
Working with SQL and JDBC(TM)
ASCII Linefeed (LF)
ASCII Carriage
return
Python
and(CR)
Java applets
ASCII Horizontal tab (TAB)
In addition, the book contains instructions for downloading and installing the Python
ASCII Vertical
languagetab
and(VT)
the Java Development Kit (JDK). Terminology, definitions, explanations,
ASCII character
withcode
octalsamples
value ooo
and numerous
make this book a useful learning experience.

ASCII character with hex value hh


Whether you are a sophisticated computer user new to programming or a serious
application
developer,
Python
Programming
with thecan
Java(TM)
String literals are identified
by the
quotes that
enclose
them. The quotes
be singleClass
(' 'Libraries
), double will
(" "),
give
you
insight
into
the
power
of
Python
and
the
know-how
to
put
it
to
work.
triple single (' ' '), or triple double ( " " " ). Here are the four styles illustrated:

>>> string1 = "Hello World"


>>> print (string1) #print the string1 to the output
Hello World

777

Python Programming with the Java Class Libraries: A Tutorial for Building

>>> string2 =Web


'Hello
World'
and Enterprise Applications with Jython
>>> print (string2)
#compare
this output to the first form
By Richard Hightower
Hello World
Publisher: Addison Wesley

>>> string3 = """Hello World"""


Pub Date: June 28, 2002
>>> print (string3) #compare this output to the 1st and 2nd form
ISBN: 0-201-61616-5
Hello
World
Table
of

Pages: 640
>>> Contents
string4 = '''Hello World'''
>>> print (string4) #compare this output to the first three forms of Strings
Characterized by ease of use, richness of expression, and concise syntax, Python has
Hello World
remained a premier programming language for more than a decade, and is used by
novices
and
In particular,
its close
relationship
to Java(TM)
If you're wondering why
there
areprofessionals
four ways toalike.
identify
literals, I intend
to tell
you, but first
I have tomakes
explain
the
two
languages,
when
used
in
combination,
ideal
for
Web
and
distributed
enterprise
escape sequences.
application development.
An escape sequence is a way to add special ASCII characters to a new line or a formfeed. As in Java and C, it's
begins
with coverage
of the basics
Using
identified in Python This
by thetutorial
backslash
(\)for
exampleof
\nsome
(newline).
Table of
2-1Python
lists theprogramming.
escape sequence
plenty
of
skill-building
exercises
and
interactive
programming
sessions,
this
book
will
characters.
help those new to programming develop an understanding of concepts and practical
techniques.
programmers,
the book demonstrates
In the following example,
we seeFor
thatexperienced
\n places the
phrase Goodbye
Earth on a Python's
new line.breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
>>> string = application
"Hello development.
Mars \n Goodbye Earth \n"

>>> print (string)


Hello Mars Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
Goodbye Earth
>>>
concepts,
including statements,
expressions,
Here we see that \t insertsFundamental
tabs betweenprogramming
Hello Mars
and Goodbye
Earth and
between Goodbye
interpreters,
and compilers
Earth and Goodbye Moon
.
PythonMars
basics, \t
including
operators,
string formatting,
namespaces,
classes, errors,
>>> string = "Hello
Goodbye
Earth
\t Goodbye
Moon"
and
exceptions
>>> print (string)
Hello Mars
Goodbye Earth
Goodbye Moon
Object-oriented programming concepts
>>>
File input/output
Escape sequences can get a little messy, especially when you add quotes or newlines to your string. Consider the
following interactive session:
Python's intrinsic functions

>>> print ("She said,


\"I
love
\" and
I said \n \"remember Paris in the
Formatting,
parsing,
andyou
manipulating
strings
spring") #one line
She said, "I loveInterfacing
you " with
andtheIJava
said
APIs and working with Java Streams
"remember Paris in the spring
>>>
Using Python and Java Swing to create GUIs
Working
with SQL
and JDBC(TM)
Python has another way, and
this is where
the different
quoting styles come in handy. Strings that use tripledouble or triple-single quotes can span multiple lines and include actual quoted lines within them. That means
Python
and Javaas
applets
that the previous example can
be rewritten
In addition,
the book
for downloading
>>> print ("""She
said,
"Icontains
loveinstructions
you", and
I said,and installing the Python
the Java
(JDK).
Terminology,
... "rememberlanguage
Parisandin
the Development
spring" Kit
""")
#two
lines definitions, explanations,
and
numerous
code
samples
make
this
book
a
useful
learning
experience.
She said, "I love you", and I said,
"remember Paris in the spring"
Whether you are a sophisticated computer user new to programming or a serious
>>>
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

Fun with Escape Characters

Publisher:
Addison
Wesley
Redo the tabs (\t
) interactive
session
with vertical tabs ( \v). You should get something weird
Date: June
28,for
2002
that looks like thePub
universal
symbol
male. Now cut and paste the output line from the DOS box
into Microsoft Word.ISBN:
(Use 0-201-61616-5
Edit->Mark from the Windows menu from the DOS box. Once the text
Table of
is selected, choose Edit->Copy
Pages: 640 Enter from the Windows menu of the DOS box, which will put the
Contents
text on the clipboard. Then return to Word and paste the text.) What happens?
Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
Numeric Literals
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
We define integer literals
in three
ways: regular (base 10), hexadecimal (base 16), and octal (base 8). This code
application
development.
shows three literals that equate to the same integer value, 255.
This tutorial begins with coverage of some of the basics of Python programming. Using
>>> base10 = plenty
255 of skill-building exercises and interactive programming sessions, this book will
>>> base16 = help
0xff
those new to programming develop an understanding of concepts and practical
>>> base8 = 0377
techniques. For experienced programmers, the book demonstrates Python's breadth of
>>> base10,base16,base8
capabilities and shows the ways that Python interfaces with Java APIs for professional
(255, 255, 255)
application development.

>>>
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
An octal starts with 0;
a hexadecimal,
with 0x. If with
you're
not familiar
octal topics
and hexadecimal
and
Enterprise Applications
Jython
covers with
important
such as: numbers, don't
worry; you don't need them to program in Python.
Exponential notation defines
floating-point
literals likeconcepts,
this:
Fundamental
programming
including statements, expressions,
interpreters, and compilers

>>> million = 1e6


>>> million
Python basics, including operators, string formatting, namespaces, classes, errors,
1000000.0
and exceptions
Object-oriented programming concepts
>>> billion = 1e+9
>>> billion
File input/output
1.0E9
Python's intrinsic functions

>>> gates_net = 36.7e+9


>>> gates_net
Formatting, parsing, and manipulating strings
3.67E10
Interfacing with the Java APIs and working with Java Streams

>>> average_income = 30e3


>>> average_income
Using Python and Java Swing to create GUIs
30000.0
Working with SQL and JDBC(TM)

>>> volts = 3e-3


Python and Java applets
>>> volts
0.003

In addition, the book contains instructions for downloading and installing the Python
and the
Development
Kit (JDK). Terminology, definitions, explanations,
We define arbitrarilylanguage
long integers
by Java
appending
an L to them.
and numerous code samples make this book a useful learning experience.

>>> bignum = 99999999999999999999999999999999999999L


>>> bignum Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
99999999999999999999999999999999999999L
give you insight into the power of Python and the know-how to put it to work.

Summary

777

In this chapter, we covered comments and document strings, which can be used to document Python code.

Unlike comments, document


strings can be accessed
the interactive
interpreter.
Python Programming
with thewith
Java
Class Libraries:
A Tutorial for Building
Web and Enterprise Applications with Jython

We looked at PythonByeasy-to-use
built-in container types (dictionaries, tuples, and lists), the values of which are
Richard Hightower
defined by literals. Literals indicate simple values of types Integer,Float,String, and Long.
Publisher: Addison Wesley

Statements are instructions to Python to perform tasks. Expressions are simple statements that return a value and
Pub Date: June 28, 2002
usually involve the use of operators. Function and class methods are made up of statements and expressions.

Table of
Contents

ISBN: 0-201-61616-5

Pages: 640

CONTENTS

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
Object-oriented programming concepts
File input/output
Python's intrinsic functions
Formatting, parsing, and manipulating strings
Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs
Working with SQL and JDBC(TM)
Python and Java applets
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
CONTENTS
Web and Enterprise Applications with Jython
By Richard Hightower

Chapter 3. Operators
and String Formatting
Publisher: Addison Wesley
Pub Date: June 28, 2002

Operators
ISBN: 0-201-61616-5
Table of
Formatting StringsModulus
Pages: 640
Contents
Summary

Characterized by ease of use, richness of expression, and concise syntax, Python has
Terms in This Chapter
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
Boolean value
application
development.
Classtutorial begins with coverage of someKeyword
This
of the basics of Python programming. Using
plenty of skill-building exercises and interactive
Literalprogramming sessions, this book will
Concatenation
help those new to programming develop an understanding of concepts and practical
techniques.
the book demonstrates Python's breadth of
Conversion For experienced programmers,Modulus
capabilities and shows the ways that Python interfaces with Java APIs for professional
Operator precedence
application
Dictionary development.
Operator
(%, Arithmetic,
Python
Programming with the Java(TM) Class
Libraries:
A TutorialBitwise,
for Building Web
Directive
Comparison,
Conditional,
and Enterprise Applications with Jython covers
important
topics suchLogical,
as:
Field
Sequence, Shift)

including statements, expressions,


Flag Fundamental programming concepts,String
interpreters, and compilers
Format directives
Tuple
Python basics, including operators, string formatting, namespaces, classes, errors,
Hexdump
Variable
and exceptions
Key Object-oriented programming concepts
In this chapter, we'll cover File
operators
and string formatting. Python string formatting controls the creation of
input/output
strings. Done correctly, it makes the production of these strings simple and straightforward.
Python's intrinsic functions
I've said it before, and I'll say it again: If you're a beginning programmer, remember that the only way to learn
Formatting,
andalong
manipulating
strings
programming is by programming,
so tryparsing,
to follow
with the interactive
sessions throughout the chapter. The
interactive interpreter mode will give you a hands-on understanding of Python operators and string formatting. If
Interfacing
withsection,
the Javajust
APIs
andover
working
with
Streams
you have trouble with an Advanced
Topic
skim
it; don't
letJava
it slow
you down.

Using
Python
and chapter
Java Swing
tobuilding
create GUIs
As in Chapter 2, most of the
concepts
in this
act as
blocks for more complex ideas. Don't worry
if something seems unclear to you at this point; you might understand it later, in a different context. For example,
Working with SQL and JDBC(TM)
logical and comparison operators may not be easily grasped here, but wait until Chapter 4, where we deal with
theif statement, which makes frequent use of these operators and so should clear things up.
Python and Java applets
If you've programmed
most
thiscontains
chapter will
be familiar.
For example,and
operators
andthe
string
formatting
In before,
addition,
the of
book
instructions
for downloading
installing
Python
in Python and C are language
very similar.
If
you
have
in-depth
programming
experience,
you
can
probably
just
skim this
and the Java Development Kit (JDK). Terminology, definitions, explanations,
material, especially ifand
you're
comfortable
with
C,
Java,
and/or
Visual
Basic.
Do,
however,
pay
attention
to the
numerous code samples make this book a useful learning experience.
following sections:
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
"Arithmetic with Strings, Lists, and Tuples"
give you insight into the power of Python and the know-how to put it to work.
"% Tuple String Formatting"

777

"Advanced Topic: Using the %d,%i,%f, and %e Directives for Formatting Numbers"

Also read the "For Programmers"


sidebar (see
pages
Python Programming
with
the5051).
Java

Operators

Class Libraries: A Tutorial for Building


Web and Enterprise Applications with Jython
By Richard Hightower
Publisher: Addison Wesley

Recall from Chapter 2 our definition of expressions as simple statements that return a value. In Python, many
Pub Date: June 28, 2002
expressions use operators, such as +, , *, and =. The following subsections describe each operator type, and
ISBN: 0-201-61616-5
each section
contains a table of the type's operators along with sample interactive sessions illustrating their use.
Table of

Pages: 640
If youContents
feel as if you've been this way before, you havewe've been using operators since Chapter 1.

Characterized by ease of use, richness of expression, and concise syntax, Python has

Arithmetic Operators
remained a premier programming language for more than a decade, and is used by

novices and professionals alike. In particular, its close relationship to Java(TM) makes
Arithmetic operatorsthe
work
the numeric
,Int, and
Long
Tableand
3-1distributed
describes them,
twowith
languages,
whentypes
usedFloat
in combination,
ideal
for .Web
enterprise
including three we have
yet to encounter:
modulus (%), which gives the remainder; exponential ( **), which
application
development.
raises one number to the power of another number; and abs, which gives a number's absolute value.
This tutorial begins with coverage of some of the basics of Python programming. Using
One example of modulus
which givesexercises
the remainder
of 1 (3/2 programming
= 1). Anothersessions,
is 10/7, this
which
gives
plentyisof3/2,
skill-building
and interactive
book
willa
remainder of 3 (10/7help
= 1 those
3/7). Innew
Python,
we express develop
the previous
sentence as of concepts and practical
to programming
an understanding
techniques. For experienced programmers, the book demonstrates Python's breadth of
>>> 10 % 7 capabilities and shows the ways that Python interfaces with Java APIs for professional
3
application development.

>>> 3 % 2
1
>>>

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

Once you understand modulus, the divmod() function, which we'll discuss in a later chapter, should come
Fundamental programming concepts, including statements, expressions,
easily to you.
interpreters, and compilers

Python basics,
including
operators, string
formatting, namespaces, classes, errors,
Table
3-1. Arithmetic
Operators
and exceptions
Operator Description
Object-oriented programming concepts
+
Addition
File input/output

Interactive Session

>>> x = 1
>>> print
3
Python's
intrinsic
functions
Subtraction
>>> x = 2
>>> print
Formatting, parsing, and manipulating strings
1
Multiplication Interfacing with the Java APIs and working with Java
>>>
x = 2
Streams
>>> print
Using Python and Java Swing to create GUIs
4

+ 2
(x)
1
(x)
* 2
(x)

Integer division returns an Integer type; float division returns Integer division:
a float type Working with SQL and JDBC(TM)

>>> x = 10 / 3
>>> print (x)
3 and installing the Python
In addition, the book contains instructions for downloading
Python and Java applets

language and the Java Development Kit (JDK). Terminology, definitions, explanations,
Float division:
and numerous code samples make this book a useful learning experience.

>>> x = 10.0 / 3.3333

Whether you are a sophisticated computer user new to programming or a serious


>>> print (x)
application developer, Python Programming with the Java(TM) Class Libraries will
3.000030000300003
give you insight into the power of Python and the know-how to put it to work.
Modulusgives the remainder; typically used for integers >>> x = 10 % 3

777

>>> print (x)


1

Exponential
Python Programming

**

>>>
x = 10**2
with the Java Class Libraries:
A Tutorial
for Building
>>> print(x)
Web and Enterprise Applications with Jython
By Richard Hightower
100

divmod Does both of the division operators at once and returns a


Publisher:
Addison
tuple; the second
item
in theWesley
tuple contains the remainder.
divmod(x,y
is equivalent
x/y,x%y
Pub Date:
June 28, to
2002

Table of
Contents

ISBN: 0-201-61616-5

This:

>>> divmod (10,3)


(3, 1)

Pages: 640

Is the same as this:

Characterized by ease of use, richness of expression, and concise syntax, Python has
>>> 10/3,10%3
remained a premier programming language for more than a decade, and is used by
(3, 1)
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web
and distributed enterprise
This:
application development.

>>> divmod (5,2)

abs

This tutorial begins with coverage of some of the basics of(2,


Python
1)programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understandingIsofthe
concepts
practical
same asand
this:
techniques. For experienced programmers, the book demonstrates Python's breadth of
>>>
capabilities and shows the ways that Python interfaces with
Java5/2,
APIs for5%2
professional
(2, 1)
application development.
Finds the absolute value of a number
>>> abs(100)
Python Programming with the Java(TM) Class Libraries:100
A Tutorial for Building Web
and Enterprise Applications with Jython covers important>>>
topicsabs(-100)
such as:

100
-, +

Sign

>>> 1,
-1, +1, +-1
Fundamental programming concepts, including statements,
expressions,
(1, -1, 1, -1)
interpreters, and compilers
Python basics, including operators, string formatting, namespaces, classes, errors,

Numeric Conversion
Operators
and exceptions

Many times we need to convert


from one numeric
type toconcepts
another. The three operators that perform this
Object-oriented
programming
conversion are Int(x),Long(x), and Float(x) , where x is any numeric value. To illustrate, in the
File input/output
example that follows we create
three numeric types: 1 ( Long),f ( Float), and i ( Integer).

Python's
>>> l,f,i=1L, 1.0,
1 intrinsic functions
The output is

Formatting, parsing, and manipulating strings

>>> l,f,i
(1L, 1.0, 1)

Interfacing with the Java APIs and working with Java Streams

Using Python and Java Swing to create GUIs


The next three examples in turn convert i to Float,f and i to Long, and l and f to Integer.
Working with SQL and JDBC(TM)

>>> float (i)


Python and Java applets
1.0
>>> float(l)
In addition, the book contains instructions for downloading and installing the Python
1.0
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
>>> long(f), long(i)
and numerous code samples make this book a useful learning experience.
(1L, 1L)
Whether you are a sophisticated computer user new to programming or a serious

>>> int(l), int(f)


application developer, Python Programming with the Java(TM) Class Libraries will
(1, 1)
give you insight into the power of Python and the know-how to put it to work.
>>>

777

Logical Operators, Comparison Operators, and Boolean Values

Logical operators arePython


a way to
express choices,
such
"This one
andLibraries:
that one or
one but
this one."
Programming
with
theasJava
Class
A that
Tutorial
fornot
Building
Comparison operators
are and
a way
to expressApplications
questions, such
as "Is
this one greater than that one?" Both work
Web
Enterprise
with
Jython
with Boolean values,Bywhich
express
the answer as either true or false. Unlike Java, Python has no true
Richard
Hightower
Boolean type. Instead, as in C, its Booleans can be numeric values, where any nonzero value must be true and
any zero value must be Publisher:
false. Thus,Addison
Python Wesley
interprets as false the following values:
Pub Date: June 28, 2002

None of
Table
Contents

ISBN: 0-201-61616-5
Pages: 640

Empty strings

Characterized by ease of use, richness of expression, and concise syntax, Python has
Empty tuples remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
Empty lists the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
Empty dictionaries
This tutorial begins with coverage of some of the basics of Python programming. Using
Zero
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
and as true all other values, including
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
Nonempty strings
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
Nonempty tuples
and Enterprise Applications with Jython covers important topics such as:
Nonempty lists
Fundamental programming concepts, including statements, expressions,
Nonempty dictionaries
interpreters, and compilers
Not zero
Python basics, including operators, string formatting, namespaces, classes, errors,
Table 3-2 describes the logical
operators. They return 1 for a true expression and 0 for a false expression. Table
and exceptions
3-3 describes the comparison operators. They return some form of true for a true expression and some form of
false for a false expression.Object-oriented programming concepts
File input/output
Logical and comparison operators
often work together to define application logic (in English, application logic
simply means decision making).When they do, they're often used with if and while statements. Don't worry
functions
aboutif and while just Python's
yet; we'llintrinsic
get into them
in detail in Chapter 4. For now, a simple way to visualize
them is to imagine that you like vanilla and chocolate ice cream but hate nuts, and you want to express your
Formatting, parsing, and manipulating strings
preference in a way that Python will understand, like this:
Interfacing with the Java APIs and working with Java Streams

if (flavor == chocolate or flavor == vanilla and \


not nuts and mycash
> and
5):Java Swing to create GUIs
Using Python
print("yummy ice cream give me some")
Working with SQL and JDBC(TM)

while(no_vanilla_left and no_chocolate_left ):


Python and
applets for me")
print ("no more
iceJava
cream
In addition, the book
contains
for downloading and installing the Python
Table
3-2.instructions
Logical Operators
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Operator Description
Interactive
Session
Python Programming with the Java Class Libraries: A Tutorial
for Building
Web
and
Enterprise
Applications
with
Jython
and
And two values or comparisons together
>>> x,y = 1,0
By Richard Hightower

>>> x and y
0
Publisher: Addison Wesley
>>> x,y = 1,1
Pub Date: June 28, 2002
>>> x and y
ISBN: 0-201-61616-5
1
Table of

Pages:
640
or Contents
Or two values together
>>> x,y = 1,0
>>> x or y
Characterized by ease of use, richness of expression, and concise syntax,
1 Python has
remained a premier programming language for more than a decade, >>>
and is x,y
used by= 0,0
novices and professionals alike. In particular, its close relationship to>>>
Java(TM)
x ormakes
y
the two languages, when used in combination, ideal for Web and distributed
enterprise
0
application development.
not
Inverse a value
>>> x,y = 0,0
>>> not xUsing
This tutorial begins with coverage of some of the basics of Python programming.
1 this book will
plenty of skill-building exercises and interactive programming sessions,
>>>
y
help those new to programming develop an understanding of concepts
andnot
practical
1
techniques. For experienced programmers, the book demonstrates Python's breadth of
>>>
x = 1
capabilities and shows the ways that Python interfaces with Java APIs
for professional
>>>
not x
application development.
0
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
Fundamental
programming
concepts, Operators
including statements, expressions,
Table
3-3. Comparison
interpreters, and compilers
Operator Description Python basics, including operators, string formatting,
Interactive
Session
namespaces,
classes, errors,
==
Equal to
>>> x,y,z=1,1,2
and exceptions

>>> x==y
1
>>> x==z
File input/output
0
Greater than or
equal intrinsic
to
>>> z>=x
Python's
functions
1
Formatting, parsing, and manipulating strings >>> x>=z
0
Interfacing
with
the
Java
APIs
and
working
with
Javaz<=x
Streams
Less than or equal to
>>>
0
Using Python and Java Swing to create GUIs
>>> x<=z
1
Working with SQL and JDBC(TM)
Greater than
>>> x>z
Python and Java applets
0
>>> z>x
In addition, the book contains instructions for downloading
and installing the Python
1
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
Less than
>>> x<z
and numerous code samples make this book a useful learning experience.
1
>>>
z<x
Whether you are a sophisticated computer user new to
programming
or a serious
0
application developer, Python Programming with the Java(TM) Class Libraries will
Not equal
toyou insight into the power of Python and the know-how
>>> x!=y
give
to put it to work.
0
>>> x!=z
1
Object-oriented programming concepts

>=

<=

>

<

!=

777

<>

Not equal
to Programming
Python

is

Publisher: Addison Wesley


Object identity

>>> x<>y
with the Java Class Libraries:
A Tutorial for Building
Web and Enterprise Applications with Jython 0
By Richard Hightower
>>> x<>z

Pub Date: June 28, 2002

1
>>> str = str2 = "hello"
>>> str is str2

ISBN: 0-201-61616-5

Table of
Contents

1
>>> str = "hi"
Characterized by ease of use, richness of expression, >>>
and concise
Python has
str syntax,
is str2
remained a premier programming language for more0than a decade, and is used by
professionals alike. In particular, its close
relationship
makes
is not Negatednovices
objectand
identity
>>>
s1 = to
s2Java(TM)
= "hello"
the two languages, when used in combination, ideal for
Web
and
distributed
enterprise
>>> s1 is not s2
application development.
0

in

Pages: 640

This tutorial begins with coverage of some of the basics of Python programming. Using
>>> s1 = s2 + " Bob"
plenty of skill-building exercises and interactive programming sessions, this book will
>>> s1 is not s2
help those new to programming develop an understanding of concepts and practical
1
techniques. For experienced programmers, the book demonstrates Python's breadth of
Checks capabilities
to see if anand
item
is inthe
a sequence
>>>
= for
[1,2,3]
shows
ways that Python interfaces
withlist
Java APIs
professional
application development.

>>> 1 in list

1 A Tutorial for Building Web


Python Programming with the Java(TM) Class Libraries:
and Enterprise Applications with Jython covers important topics such as:
>>> 4 in list
0
Fundamental programming concepts, including statements, expressions,
not in Checks to see if an item is NOT in a sequence
>>> list = [1,2,3]
interpreters, and compilers

>>> 1namespaces,
not in classes,
list errors,
Python basics, including operators, string formatting,
0
and exceptions
Object-oriented programming concepts

>>> 4 not in list


1

File input/output

Advanced Topic: Logical


Operators
Python's intrinsic
functionsand Boolean Returns
Comparison operators always
return either
1 or and
0 of manipulating
type Integer
.
Formatting,
parsing,
strings

>>> 1 > 2
0
>>> 1 < 2
1

Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs

Working with SQL and JDBC(TM)


Logical operators can return more than the Integer types 1 or 0, as we see in the following expression, which
Python
and Java applets
determines if 0 or (1,2,3)
is true.
In addition, the book contains instructions for downloading and installing the Python
>>> 0 or (1,2,3)
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
(1, 2, 3)
and numerous code samples make this book a useful learning experience.
Python equates 0 to false and a nonempty tuple (1, 2, 3) to true, so the logical operator returns the true
you tuple
are a sophisticated
computer user new to programming or a serious
statement, that is, theWhether
(1,2,3)
literal.
application developer, Python Programming with the Java(TM) Class Libraries will
give you
insight into
of Python
know-how to put it to work.
The following expression
determines
if 1the
< power
2 or the
integer and
5 is the
true:

>>> 1 < 2 or 5
1

777

Because1 < 2 is true,


the expression
returns
1, which
equates
to true,
but it equates
5 to for
trueBuilding
as well;
Python
Programming
with
the Java
Class
Libraries:
A Tutorial
however, only the first
trueand
statement
in an Applications
or statement with
(1 above)
is returned.
Web
Enterprise
Jython
By Richard Hightower

The next expression also determines if 1 < 2 or the integer 5 is true, but this time we swap the operands.
Publisher: Addison Wesley

>>> 5 or 1 < 2
Pub Date: June 28, 2002
5

Once

Table of
again,
only the
Contents

ISBN: 0-201-61616-5
Pages:
640 is
first true
statement

returned, which is now 5.

Likeor,and returnsCharacterized
the first true operand.
However,
andof
is expression,
unlike or inand
thatconcise
only the
last operand
by ease of
use, richness
syntax,
Python can
has make
remained a premier programming language for more than a decade, and is used by
it true.
novices and professionals alike. In particular, its close relationship to Java(TM) makes
>>> (1,1) andthe[2,2]
two languages, when used in combination, ideal for Web and distributed enterprise
[2, 2]
application development.

>>> [2,2] and (1,1)


(1, 1)
This tutorial begins with coverage of some of the basics of Python programming. Using
>>> [2,2] andplenty
(3,3)
and {"four":4}
of skill-building
exercises and interactive programming sessions, this book will
{'four': 4} help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
Conversely, the first capabilities
occurrencesand
of ashows
false are
and. interfaces with Java APIs for professional
the returned
ways thatbyPython
application development.

>>> [1,1] and {} and ()


{}
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
>>> (1,1) andand[]
and {}
Enterprise
Applications with Jython covers important topics such as:
[]

For

Fundamental programming concepts, including statements, expressions,


interpreters, and compilers
Programmers:
Conditional Operators in Other

Languages
Python basics, including
operators, string formatting, namespaces, classes, errors,
and exceptions
C, C++, and Java have a conditional operator that works conveniently as shorthand for and and
Object-oriented
programming
concepts are equivalent:
or. In Java, for example,
the following
two if statements
File input/output
val = boolean_test
?

true_return : false_return;

Python's intrinsic functions

if (boolean_test)
val = Formatting,
true_return;
parsing, and manipulating strings
else
val = Interfacing
false_return;
with the Java APIs and working with Java Streams
Python has no conditional
operator,
butJava
youSwing
can simulate
one
with the form
Using Python
and
to create
GUIs

val = (boolean_test
\
Working withand
SQL true_return)
and JDBC(TM)
or false_return
Python and Java applets
This works because or always returns the first true statement and and always returns the last one,
In addition,are
theequivalent:
book contains instructions for downloading and installing the Python
so these two statements
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
>>> if ( and
3 numerous
> 5): code samples make this book a useful learning experience.

...
num = 1
Whether you are a sophisticated computer user new to programming or a serious
... else:
application
...
num
= 2 developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.
...
>>>num
2

777

>>> num = (3>5 and 1) or 2

>>> num
2

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

The following two expressions are also equivalent:


Publisher: Addison Wesley

>>> if ( 5 > 3):


Pub Date: June 28, 2002
...
num
= 1
ISBN: 0-201-61616-5
...
else:
Table of
Pages:
...
num = 2 640
Contents
...
>>>num Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
1

novices and professionals alike. In particular, its close relationship to Java(TM) makes
the(5>3
two languages,
when
>>> num =
and 1)
orused
2 in combination, ideal for Web and distributed enterprise
application
development.
>>> num

This tutorial begins with coverage of some of the basics of Python programming. Using
plenty
of skill-building
exercises
and interactive
programming sessions,
this book will
Be warned: This
simulation
works only
if the expressions
true_return
and
help
those
new
to
programming
develop
an
understanding
of
concepts
and
practical
false_return are not equivalent to false. If we need them to be false, we can do something
techniques.
For
experienced
programmers,
the
book
demonstrates
Python's
breadth of
like this:
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
>>> true_return
= 0

>>> false_return = 2
Python
with the Java(TM) Class\Libraries: A Tutorial for Building Web
>>> num =
(5 Programming
> 3 and [true_return])
and
Enterprise
Applications
with Jython covers important topics such as:
or [false_return]
>>> num
[0]
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
Now the num variable is equivalent to a list containing one element, but this isn't exactly what we
want. However, since
this code
is returning
list, we can
put the
entire expression
to the
left oferrors,
the
Python
basics,
includingaoperators,
string
formatting,
namespaces,
classes,
assignment operatorand
in parentheses,
which
will
achieve
our
desired
result.
exceptions

>>> num = ((5


> 3 and programming
[true_return])
Object-oriented
concepts or [false_return])[0]
>>> num
0
File input/output
To sum up, Python'sPython's
bulletproof
equivalent
of the conditional operator is
intrinsic
functions

val = ((boolean_test
and and
[true_return])
Formatting, parsing,
manipulating strings \
or [false_return])[0]
Interfacing with the Java APIs and working with Java Streams
which is no more verbose than another Python expression:
Using Python and Java Swing to create GUIs

if (boolean_test): val = true_return


with SQL and JDBC(TM)
else: val = Working
false_return
Python
and Javaoperator
applets is hard to understand and use, so go easy with it.
Python's version of the
conditional
Perhaps one day Python will have a conditional operator of its own (and, I might add, its own +=
operator). In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.

Advanced Topic: Bitwise and Shift Operators


Whether you are a sophisticated computer user new to programming or a serious
application
developer, Python
Programming
with thealgebra,
Java(TM)
Libraries
will
If you lack experience
with any programming
language
or with Boolean
youClass
should
ignore bitwise
give
you
insight
into
the
power
of
Python
and
the
know-how
to
put
it
to
work.
operators. Another reason to ignore them is that they're usually associated with low-level programming, and
you're learning Python, which is much higher level than C, C++, or even Java. If for some reason you're curious
about bitwise operators, any introductory C text will tell you all you need to know. The same goes for shift
operators.

777

Just for the sake of completeness,


Table 3-4 describes
operator
To understand
youBuilding
need to know
Python Programming
with the both
Java
Class types.
Libraries:
A Tutorialit,for
something of hexadecimal
andEnterprise
Boolean algebra.
(See Chapter
for an example of a hexdump file viewer,
Web and
Applications
with 10
Jython
which uses the shift By
operators.)
Richard Hightower
Publisher: Addison Wesley
Operator Precedence
Pub Date: June 28, 2002
ISBN:the
0-201-61616-5
Operator
precedence determines
order in which Python evaluates the parts of a statement. It generally
Table of

Pages:
640
follows
the operator precedence you learned in high school algebra and is nearly identical to that used in any
Contents
other common programming language. Here's an example in which y/z is processed before 2 + y, rendering
by ease of use, richness of expression, and concise syntax, Python has
x equal to 4 and notCharacterized
6.
remained a premier programming language for more than a decade, and is used by
>>> x,y,z=1,4,2
novices and professionals alike. In particular, its close relationship to Java(TM) makes
>>> x = 2 + ythe/two
z languages, when used in combination, ideal for Web and distributed enterprise
>>> x
application development.

4
This tutorial begins with coverage of some of the basics of Python programming. Using
When in doubt as toplenty
whichof
operator
will be exercises
evaluatedand
first,interactive
use parentheses.
They prevent
many
mistake
skill-building
programming
sessions,
thisabook
willif you
use them to force precedence,
enhance codedevelop
readability.
help thoseand
newthey
to programming
an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
You may occasionally
want to force
a precedence
other
the algebraic
to make
explicit. The
capabilities
and shows
the ways
thatthan
Python
interfacesdefault
with Java
APIs itformore
professional
following example shows
how
to
do
this:
application development.

>>> x,y,z = 1,4,2


Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
>>> x = 2 + (y/z)
and Enterprise Applications with Jython covers important topics such as:
>>> x
4
Fundamental programming concepts, including statements, expressions,
>>> x = (2+y) /z interpreters, and compilers

>>> x
3

Python basics, including operators, string formatting, namespaces, classes, errors,


and exceptions
The choice of precedence here depends on which expression2 + y or y/zis to be evaluated first. Note,
programming
concepts
though, that the value of xObject-oriented
changes according
to the grouping
and ends up as either 4 or 3. The first expression,
2 + y/z, is unnecessary except to adorn the code with parentheses for clarity, which is important for code
File input/output
maintainability.
Python's intrinsic functions
Visitwww.python.org for a detailed description of operator precedence. For now, the following list shows all
operators in their precedence
order: parsing, and manipulating strings
Formatting,
[],(),{},''
Parentheses,
string
Interfacing
with the
Javaconversion
APIs and working with Java Streams
seq[index]
Indexing sequences or dictionaries
Using Python and Java Swing to create GUIs
integer.MAX_INT
Attribute reference
~I
Bit inversion
Working
with SQL and JDBC(TM)
-i,+i
Unary minus, unary plus
Python and Java applets
* ,/ ,%
Multiplication, division, modulus
+ ,In addition,Addition,
the booksubtraction
contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.

Whether you are a sophisticated computer user new to programming or a serious


application developer,
Python
Programming
the Java(TM) Class Libraries will
Table 3-4.
Bitwise
and Shiftwith
Operators
give you insight into the power of Python and the know-how to put it to work.

777

Operator

<<

Description
Session
Python
Programming with theInteractive
Java Class
Libraries: A Tutorial for Building
Web Shift
and Enterprise
Applications
with
Jython
left
>>> # binary 1111 1111
By Richard Hightower
>>> x = 0xff
Publisher: Addison Wesley
Pub Date: June 28, 2002

Table of
Contents

>>

ISBN: 0-201-61616-5

>>> # z = 0011 1111 1100


>>> z = x << 2 >>> print (x)
255

Pages: 640

>>> print (z)


Characterized by ease of use, richness
1020of expression, and concise syntax, Python has
remained
a
premier
programming
language
than a decade, and is used by
Shift right
>>>
# zfor=more
1020
novices and professionals alike. In
particular,
its
close
to Java(TM) makes
>>> #z = 1111 relationship
1111
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
>>> z = z >> 2

>>> z

&

This tutorial begins with coverage of some of the basics of Python programming. Using
255
plenty of skill-building exercises and interactive programming sessions, this book will
Bitwise
and
>>> #anyunderstanding
= binaryof0000
1010
help those new to programming develop
concepts
and practical
>>>
y
=
0x0A
techniques. For experienced programmers, the book demonstrates Python's breadth of
>>>Python
print
(y) with Java APIs for professional
capabilities and shows the ways that
interfaces
10
application development.

>>> print
(x) A Tutorial for Building Web
Python Programming with the Java(TM)
Class Libraries:
and Enterprise Applications with255
Jython covers important topics such as:
>>> z = y & z
Fundamental programming>>>
concepts,
including
print
(z) statements, expressions,
interpreters, and compilers10

Bitwise
>>> #continued
example
Pythonor
basics, including operators,
string formatting,
namespaces, classes, errors,
>>>
z
=
y
|
x
and exceptions

>>> print (z)


255concepts
Object-oriented programming
BitwiseXOR
>>> z = y ^ x
File input/output
>>> z
245
Python's intrinsic functions
Bitwisenot
>>> y = 0xffffffff
>>> y
Formatting, parsing, and manipulating
strings
-1

Interfacing with the Java APIs and working with Java Streams

>>> z = ~y
Using Python and Java Swing
create GUIs
>>>to z

Working with SQL and JDBC(TM)


Python and Java applets
<<,>>

Bit shifting,
left andthe
right
In addition, the book contains instructions for downloading
and installing
Python
language and the Java Development Kit (JDK). Terminology,
Bitwise definitions,
operator orexplanations,
,and,xor
[bar], &, ^
numerous
code
samples
experience.
<,>,>=,<=,==,isand
not
,is,!=,
<>,in
,not make
in this book a useful learning
Comparison
operators
not
not or a serious
Whether you are a sophisticated computer user new to Logical
programming
and
application developer, Python Programming with the Java(TM)
Class Libraries will
Logical and
give
you
insight
into
the
power
of
Python
and
the
know-how
to
put
or
Logical or it to work.

777

Arithmetic with Strings, Lists, and Tuples

As in Java, the addition


operator
( +) in Python
works
string
types
to concatenate,
that is,
strings.
Python
Programming
with
thewith
Java
Class
Libraries:
A Tutorial
forlink
Building
(Recall that we usedWeb
+ on and
strings
in Chapter
1.) Unlike inwith
Java,Jython
the multiplication operator (*) in Python is used
Enterprise
Applications
to repeat string values.
ConsiderHightower
the following interactive session:
By Richard

>>> love = "I love


my family" + (" very " * 4) + "much!"
Publisher: Addison Wesley
>>> love
Pub Date: June 28, 2002
'I love my family very very very very much!'

ISBN: 0-201-61616-5
Table of
Pages: 640
Contents
hugs_and_kisses = "XO" * 20

>>>
>>> hugs_and_kisses
Characterized by ease of use, richness of expression, and concise syntax, Python has
'XOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXO'

remained a premier programming language for more than a decade, and is used by
novices andthe
professionals
particular,
its close
relationship
to Java(TM)
makes by
In the first line, we concatenate
string "I alike.
loveIn my
family"
with
the string "very"
multiplied
the
two
languages,
when
used
in
combination,
ideal
for
Web
and
distributed
enterprise
4, which gives "very very very very". If we want to sign our letter with hugs and kisses (Xs and Os),
application
we can multiply to save
time in adevelopment.
similar way.
This tutorial
beginsfor
with
coverage of some of the basics of Python programming. Using
Addition and multiplication
also work
lists.
plenty of skill-building exercises and interactive programming sessions, this book will
those new to"Monica",
programming develop
an understanding
of concepts and practical
>>> friends =help
["Joey",
"Ross",
"Chandler"]
techniques.
For
experienced
programmers,
the
book
demonstrates
Python's breadth of
>>> old_friends = ["Fonz", "Ritchie", "Potsy"]
capabilities
and
shows
the
ways
that
Python
interfaces
with
Java
APIs
for professional
>>> strange_cast = friends + old_friends
application development.
>>> strange_cast

['Joey', 'Monica', 'Ross', 'Chandler', 'Fonz', 'Ritchie', 'Potsy']


Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
Enterprise Applications with Jython covers important topics such as:
They work for tuplesand
as well.

>>>
>>>
>>>
>>>
(1,

tuple1 =
tuple2 =
tuple3 =
tuple3
2, 3, 4,

(1,2,3,4)
Fundamental
programming
("5",
6L, 7.0,
0x8) concepts, including statements, expressions,
interpreters,
and compilers
tuple1
+ tuple2
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions

'5', 6L, 7.0, 8)

>>> tuple4 = tuple1


* 2
Object-oriented
programming concepts
>>> tuple4
(1, 2, 3, 4, 1, 2,
3, 4)
File input/output
Python's intrinsic functions
Sequence Operators
Formatting, parsing, and manipulating strings
We've been using sequence operators since Chapter 1, so you've seen most of them. However, some of the
operators in Table 3-5 willInterfacing
be new to you.
with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs
Table 3-5. Sequence Operators
Working with SQL and JDBC(TM)
Python and Java applets
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Operator Description
Interactive
Session
Python Programming with the Java
Class Libraries:
A Tutorial for Building
Web
and
Enterprise
Applications
with
Jython
[index] Get the indexed item
>>> nums = (0,1,2,3,4,5,6,7,8,9)
By Richard Hightower

>>> nums[0]
0

Publisher: Addison Wesley


Pub Date: June 28, 2002

Table of
Contents

[:]

ISBN: 0-201-61616-5

>>> nums[1]
1

Pages: 640

Slice notation
>>> nums = (0,1,2,3,4,5,6,7,8,9)
Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language
more than
>>>fornums
[:]a decade, and is used by
novices and professionals alike. In particular,
its
close
to Java(TM)
(0, 1, 2, relationship
3, 4, 5,
6, 7, makes
8, 9)
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
>>> nums [5:]

(5, 6, 7, 8, 9)

len()

This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
>>> nums [:5]
help those new to programming develop an understanding of concepts and practical
(0, 1, 2, 3, 4)
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
Lengthapplication development.
>>> nums = (0,1,2,3,4,5,6,7,8,9)
Python Programming with the Java(TM)>>>
Classlen
Libraries:
A Tutorial for Building Web
(nums)
and Enterprise Applications with Jython1covers important topics such as:

max()

Get the largest


item in theprogramming
sequence concepts,
>>>including
nums statements,
= (0,1,2,3,4,5,6,7,8,9)
Fundamental
expressions,
interpreters, and compilers

>>> max(nums)
9 string formatting, namespaces, classes, errors,
Python basics, including operators,
and exceptions
>>> letters = "abcdefg"
Object-oriented programming concepts
>>> max (letters)

'g'
File input/output

min()

Python's intrinsic functions


Get the smallest item in the sequence
>>> nums = (0,1,2,3,4,5,6,7,8,9)
Formatting, parsing, and manipulating strings

>>> min(nums)
Interfacing with the Java APIs and
0 working with Java Streams
Using Python and Java Swing to create
>>> GUIs
letters = "abcdefg"
Working with SQL and JDBC(TM)
>>> min (letters)
Python and Java applets

'a'

In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.

Formatting StringsModulus

Whether you are a sophisticated computer user new to programming or a serious


Although not actually
modulus, developer,
the Python Python
% operator
works similarly
in string
formatting
interpolate
application
Programming
with the
Java(TM)
Class to
Libraries
will
variables into a formatting
string.
If you've
programmed
in C, you'll
notice
that % is
C's printf() ,
give you
insight
into the
power of Python
and the
know-how
tomuch
put it like
to work.
sprintf(), and fprintf() functions.

777

There are two forms of %, one of which works with strings and tuples, the other with dictionaries.

StringOperandPython
% TupleOperand
Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython

StringOperandByRichard
% DictionaryOperand
Hightower
Both return a new formatted
stringAddison
quicklyWesley
and easily.
Publisher:
Pub Date: June 28, 2002

% Tuple String Formatting


ISBN: 0-201-61616-5

Table of
Contents

Pages: 640

In the StringOperand % TupleOperand form, StringOperand represents special directives


within the string thatCharacterized
help format the
One
directive
is %s, which
up thesyntax,
formatPython
string has
bytuple.
ease of
use,such
richness
of expression,
andsets
concise
remained a premier programming language for more than a decade, and is used by
>>> format = novices
"%s is
my friendalike.
and
%s is %s
years
old" to Java(TM) makes
and professionals
In particular,
its close
relationship
the two languages, when used in combination, ideal for Web and distributed enterprise
and creates two tuples, Ross_Info and Rachael_Info.
application development.

>>> Ross_InfoThis
= tutorial
("Ross",
"he", 28)
begins with coverage of some of the basics of Python programming. Using
>>> Rachael_Info
=
("Rachael",
"she", 28)
plenty of skill-building exercises and interactive programming sessions, this book will
help those
newbe
toused
programming
developstatement,
an understanding
of concepts
andevery
practical
The format string operator
(%) can
within a print
where you
can see that
occurrence
techniques.
For
experienced
programmers,
the
book
demonstrates
Python's
breadth of
of%s is respectively replaced by the items in the tuple.
capabilities and shows the ways that Python interfaces with Java APIs for professional
application
>>> print (format
% development.
Ross_Info)

Ross is my friend and he is 28 years old

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise
Applications with Jython covers important topics such as:
>>> print (format
% Rachael_Info)

Rachael is my friend and she is 28 years old


Fundamental programming concepts, including statements, expressions,
Also note that %s automatically converts the last item in the tuple to a reasonable string representation. Here's an
interpreters, and compilers
example of how it does this using a list:
Python basics, including operators, string formatting, namespaces, classes, errors,
>>> bowling_scores
= [190, 135, 110, 95, 195]
and exceptions

>>> name = "Ross"Object-oriented programming concepts


>>> strScores = "%s's
bowling scores were %s" \
File input/output
...
% (name, bowling_scores)
Python's intrinsic functions
>>> print strScores
Ross's bowling scores were [190, 135, 110, 95, 195]
Formatting, parsing, and manipulating strings
First, we create a list variable called bowling_scores and then a string variable called name. We then use
with the Java APIs
anduse
working
Java Streams
a string literal for a format Interfacing
string (StringOperand
) and
a tuplewith
containing
name and
bowling_scores.
Using Python and Java Swing to create GUIs

Format Directives Working with SQL and JDBC(TM)


and Java applets
Table 3-6 covers all of the Python
format directives
and provides a short example of usage for each. Note that the tuple
argument containing a single item can be denoted with the % operator as item, or (item).
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous codeTable
samples
make
this book
a useful learning experience.
3-6.
Format
Directives
Whether you are a sophisticated computer user new to programming or a serious
Directive Description
Interactive
application developer, Python Programming
with theSession
Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Represents
a value
as a stringwith the Java
>>>
list
= ["hi",
1,for1.0,
1L]
Python
Programming
Class
Libraries:
A Tutorial
Building

%s

>>>
"%s" %
Web and Enterprise Applications with
Jython
By Richard Hightower
"['hi', 1,
Publisher: Addison Wesley
Pub Date: June 28, 2002

Integer

%i

%d

ISBN: 0-201-61616-5

Table of
Contents

Pages: 640

list
1.0, 1L]"

>>> "list equals %s" % list


"list equals ['hi', 1, 1.0, 1L]"
>>> "i = %i" % (5)
'i = 5'

Characterized by ease of use, richness of>>>


expression,
concise
"i = and
%3i"
% syntax,
(5) Python has
remained a premier programming language
'i for
= more
5' than a decade, and is used by
relationship
Decimalnovices
integerand professionals alike. In particular,
>>> its
"dclose
= %d"
% 5 to Java(TM) makes
the two languages, when used in combination,
ideal
for
Web
and distributed enterprise
'd = 5'
application development.

>>> "%3d" % (3)

%x

This tutorial begins with coverage of some of the basics of Python programming. Using
' 3'
plenty of skill-building exercises and interactive programming sessions, this book will
Hexadecimal
integer
"%x" % (0xff)
help those new to programming develop>>>
an understanding
of concepts and practical
'ff'
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
>>> "%x" % (255)
application development.

'ff'

%x

Pythoninteger
Programming with the Java(TM)>>>
Class"%x"
Libraries:
A Tutorial for Building Web
Hexadecimal
% (0xff)
and Enterprise Applications with Jython'ff'
covers important topics such as:

>>> "%x" % (255)

%o

Octal integer

Fundamental programming concepts, including statements, expressions,


'ff'
interpreters, and compilers

>>> "%o" % (255)

377
Python basics, including operators,
string formatting, namespaces, classes, errors,
and exceptions
>>> "%o" % (0377)
Object-oriented programming concepts
377

%u

Unsigned integer
File input/output

>>> print "%u" % -2000


2147481648

Python's intrinsic functions

%e

>>> print "%u" % 2000


2000strings
Formatting, parsing, and manipulating
Float exponent
>>> print "%e" % (30000000L)
Interfacing with the Java APIs and
working with Java Streams
3.000000e+007
Using Python and Java Swing to create
>>> GUIs
"%5.2e" % (300000000L)

'3.00e+008'
>>> "check = %1.2f" % (3000)
'check = 3000.00'

Working with SQL and JDBC(TM)

%f

Float

Python and Java applets

%g

In addition, the book contains instructions


for "payment
downloading and
the %
Python
>>>
= installing
$%1.2f"
3000'
language and the Java Development Kitpayment
(JDK). Terminology,
definitions, explanations,
=$3000.00'
and numerous code samples make this book
useful learning
Float exponent
>>> a "%3.3g"
% experience.
100

'100.'

Whether you are a sophisticated computer user new to programming or a serious


application developer, Python Programming with the Java(TM) Class Libraries will
>>> "%3.3g" % 1000000000000L
give you insight into the power of Python and the know-how to put it to work.

'10.e11'

777

>>> "%g" % 100


'100.'

%c

ASCII character
Python Programming

>>>
"%c"
% (97)
with the Java
Class
Libraries:
A Tutorial for Building
'a'
Web and Enterprise Applications with
Jython
By Richard Hightower
Publisher: Addison Wesley

>>> "%c" % 97
'a'

Pub Date: June 28, 2002


Table of

Contents

ISBN: 0-201-61616-5
Pages: 640

>>> "%c" % (97)


'a'

Table 3-7 shows howCharacterized


flags can be used
with
directives
to add leading
zeroes
or spaces
to ahas
formatted
by ease
ofthe
use,format
richness
of expression,
and concise
syntax,
Python
number. They shouldremained
be inserted
immediately
after the language
%.
a premier
programming
for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
Table 3-7. Format Directive Flags
application development.

basics of Python
programming. Using
Flag DescriptionThis tutorial begins with coverage of some of the Interactive
Session
plenty
of
skill-building
exercises
and
interactive
programming
sessions,
this book will
#
Forces octal to have a 0 prefix; forces hex to have a 0x >>> "%#x" % 0xff
help
those
new
to
programming
develop
an
understanding
of
concepts
and
practical
prefix
'0xff'
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces
Java APIs
for professional
>>> with
"%#o"
% 0377
application development.
'0ff'

+
-

Forces a positive
to havewith
a sign
>>> "%+d"
% 100
Pythonnumber
Programming
the Java(TM) Class Libraries:
A Tutorial
for Building Web
'+100'topics such as:
and Enterprise Applications with Jython covers important
Left justification (default is right)
>>> "%-5d, %-5d" % (10,10)

'10 , 10 '

Fundamental programming concepts, including statements, expressions,


" " Precedes a positive
number with a blank space
>>> "% d,% d" % (-10, 10)
interpreters, and compilers

'-100,10'
0 padding instead Python
of spaces
>>> "%05d"
% (100,)
basics, including operators, string formatting,
namespaces,
classes, errors,
'00100'
and exceptions
Object-oriented programming concepts

Advanced Topic: Using the %d, %i, %f, and %e Directives for Formatting
Numbers
File input/output
Python's
intrinsic
functions
The% directives format numeric
types:
%i works
with Integer;%f and %e work with Float with and
without scientific notation, respectively.
Formatting, parsing, and manipulating strings

>>> "%i, %f, %e" % (1000, 1000, 1000)


Interfacing with the Java APIs and working with Java Streams
'1000, 1000.000000, 10.000000e+002'
Using Python and Java Swing to create GUIs
Notice how awkward all of those zeroes look. You can limit the length of precision and neaten up your code like
this:
Working with SQL and JDBC(TM)

>>> "%i, %2.2f, %2.2e"


(1000,
Python and%Java
applets 1000, 1000)
'1000, 1000.00, 10.00e+002'
In addition, the book contains instructions for downloading and installing the Python
The%2.2f directivelanguage
tells Python
the number asKit
at (JDK).
least two
characters and
to cut theexplanations,
precision to two
and to
theformat
Java Development
Terminology,
definitions,
characters after the decimal
point.
This
is
useful
for
printing
floating-point
numbers
that
represent
currency.
and numerous code samples make this book a useful learning experience.

>>> "Your monthly


payments
are $%1.2f"
% (payment)
Whether you
are a sophisticated
computer user
new to programming or a serious
'Your monthlyapplication
payments
are
$444.43'
developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.
All% directives have the form %min.precision(type), where min is the minimum length of the field,
precision is the length of the mantissa (the numbers on the right side of the decimal point), and type is
the type of directive (e,f,i, or d). If the precision field is missing, the directive can take the form
%min(type), so, for example, %5d ensures that a decimal number has at least 5 fields and %20f ensures
that a floating-point number has at least 20.

777

Python Programming with the Java Class Libraries: A Tutorial for Building

Let's look at the use Web


of these
directives
in anApplications
interactive session.
and
Enterprise
with Jython
By Richard Hightower

>>> "%5d" % (100,)


'
100'
Publisher: Addison Wesley
>>> "%20f" % (100,)
Pub Date: June 28, 2002
'
100.000000'
ISBN: 0-201-61616-5
Table of

Pages:
Here'sContents
how to truncate the float640
's mantissa to 2 with %20.2f.

>>> "%20.2f" Characterized


% (100,) by ease of use, richness of expression, and concise syntax, Python has
'
100.00'
remained
a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
The padding that precedes
directive when
is useful
forinprinting
rows and
columns
ofand
datadistributed
for reporting
because it
the twothe
languages,
used
combination,
ideal
for Web
enterprise
makes the printed output
easy todevelopment.
read. This can be seen in the following example (from format.py):
application

# Create two
rows begins with coverage of some of the basics of Python programming. Using
This tutorial
row1 = (100, plenty
10000,
20000, exercises
50000,and6000,
6,programming
5)
of skill-building
interactive
sessions, this book will
row2 = (1.0, help
2L,those
5,new
2000,
56, 6.0,
7) an understanding of concepts and practical
to programming
develop
techniques. For experienced programmers, the book demonstrates Python's breadth of

#
capabilities and shows the ways that Python interfaces with Java APIs for professional
# Print out
the rows
without formatting
application
development.
print "here is an example of the columns not lining up"
print `row1` Python
+ "\n"
+ `row2`
Programming
with the Java(TM) Class Libraries: A Tutorial for Building Web
print
and Enterprise Applications with Jython covers important topics such as:
#
# Create a format string that forces the number
Fundamental
programming long
concepts,
statements, expressions,
# to be at least
3 characters
toincluding
the left
interpreters,
compilers
# and 2 characters
toand
the
right of the decimal point
format = "(%3.2e, %3.2e, %3.2e, %3.2e, " + \
Python basics, including operators, string formatting, namespaces, classes, errors,
"%3.2e, %3.2e, %3.2e)"
and exceptions

#
Object-oriented programming concepts
# Create a string for both rows
# using the format
operator
File input/output
strRow1 = format % row1
intrinsic functions
strRow2 = format Python's
% row2
print "here is an example of the columns" + \
" lining upFormatting,
using parsing,
\%e" and manipulating strings
Interfacing
with the Java APIs and working with Java Streams
print strRow1 + "\n"
+ strRow2
print
Using Python and Java Swing to create GUIs

# Do it again Working
this time
with
the %i and %d directive
with SQL
and JDBC(TM)
format1 = "(%6i, %6i, %6i, %6i, %6i, %6i, %6i)"
format2 = "(%6d, Python
%6d,and
%6d,
%6d, %6d, %6d, %6d)"
Java applets
strRow1 = format1 % row1
In addition,
book contains instructions for downloading and installing the Python
strRow2 = format2
% the
row2
language
and the Java of
Development
Kit (JDK). Terminology,
definitions, explanations,
print "here is
an example
the columns"
+ \
and numerous
code\%i
samples
make
this book a useful learning experience.
" lining
up using
and
\%d"
you are
sophisticated computer user new to programming or a serious
print strRow1Whether
+ "\n"
+ astrRow2
application
developer,
Python Programming with the Java(TM) Class Libraries will
print
give you insight into the power of Python and the know-how to put it to work.

here is an example of the columns not lining up


(100, 10000, 20000, 50000, 6000, 6, 5)
(1.0, 2L, 5, 2000, 56, 6.0, 7)

777

here is an example
of the columns
lining
usingA Tutorial
\%e
Python Programming
with the Java
Classup
Libraries:
for Building
(1.00e+002, 1.00e+004,
2.00e+004,
6.00e+003, 6.00e+000, 5.00e+000)
Web and Enterprise
Applications5.00e+004,
with Jython
(1.00e+000, 2.00e+000,
5.00e+000, 2.00e+003, 5.60e+001, 6.00e+000, 7.00e+000)
By Richard Hightower
here is an example
ofAddison
the Wesley
columns lining up using \%i and \%d
Publisher:
( 100,
10000,
20000,
6000,
6,
5)
Pub Date: June 28, 2002 50000,
(
1,
2, ISBN: 0-201-61616-5
5,
2000,
56,
6,
7)

Table of

Pages: 640

Contents
You can
see that the %3.2e directive permits a number to take up only three spaces plus the exponential
whereas%6d and %6i permit at least six spaces. Note that %i and %d do the same thing that %e does. Most C
Characterized by ease of use, richness of expression, and concise syntax, Python has
programmers are familiar with %d but may not be familiar with %i, which is a recent addition to that language.
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
String % Dictionary
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
Another useful Python feature for formatting strings is StringOperand %DictionaryOperand.
tutorial begins
withnamed
coverage
of some
the basics
of Python programming.
Using
This form allows youThis
to customize
and print
fields
in theof
string.
%(Income)d
formats the value
plenty
of
skill-building
exercises
and
interactive
programming
sessions,
this
book
will
referenced by the Income key. Say, for example, that you have a dictionary like the one here:
help those new to programming develop an understanding of concepts and practical
Monica = { techniques. For experienced programmers, the book demonstrates Python's breadth of
"Occupation":
"Chef",
capabilities and shows
the ways that Python interfaces with Java APIs for professional
"Name"
:
"Monica",
application development.

"Dating" : "Chandler",
Python Programming
"Income"
: 40000with the Java(TM) Class Libraries: A Tutorial for Building Web
and
Enterprise
Applications with Jython covers important topics such as:
}
With%(Income)d, this is expressed as
Fundamental programming concepts, including statements, expressions,
and compilers
>>> "%(Income)d" interpreters,
% Monica

'40000'
Python basics, including operators, string formatting, namespaces, classes, errors,
andbest
exceptions
Now let's say you have three
friends, whom you define as dictionaries named Monica,Chandler , and
Ross.
Object-oriented programming concepts

Monica =

Ross =

{
File input/output "Chef",
"Occupation":
"Name" : "Monica",
Python's intrinsic functions
"Dating" : "Chandler",
"Income"
: parsing,
40000and manipulating strings
Formatting,
}
{ with the Java APIs and working with Java Streams
Interfacing
"Occupation": "Scientist Museum Dude",
"Name"
"Ross",
Using :Python
and Java Swing to create GUIs
"Dating" : "Rachael",
Working :
with70000
SQL and JDBC(TM)
"Income"
}
Python and Java applets

Chandler =

In addition, the book contains instructions for downloading and installing the Python
"Occupation": "Buyer",
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
"Name" : "Chandler",
and numerous code samples make this book a useful learning experience.

"Dating" : "Monica",
"Income"
65000
Whether
you are:a sophisticated
computer user new to programming or a serious
}
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.
To write them a form letter, you can create a format string called message that uses all of the above
dictionaries' keywords.

777

message = "%(Name)s, %(Occupation)s, %(Dating)s," \


"
%(Income)2.2f"

Python Programming with the Java Class Libraries: A Tutorial for Building

Notice that %(Income)2.2f formats this with a floating-point precision of 2, which is good for currency.
Web and Enterprise Applications with Jython
The output is
By Richard Hightower

Chandler, Buyer, Monica, 65000.00


Addison Wesley
Ross, ScientistPublisher:
Museum
Dude, Rachael, 70000.00
Pub
Date:
June
2002
Monica, Chef, Chandler, 28,
40000.00
Table of

ISBN: 0-201-61616-5

Pages: 640
Youcan
then print each dictionary
using the format string operator.
Contents

print messageCharacterized
% Chandler
by ease of use, richness of expression, and concise syntax, Python has
print messageremained
% Ross
a premier programming language for more than a decade, and is used by
print messagenovices
% Monica
and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
To generate your form
letter anddevelopment.
print it out to the screen, you first create a format string called dialog.
application

dialog = """ This tutorial begins with coverage of some of the basics of Python programming. Using
Hi %(Name)s, plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical

How are you doing?


is %(Dating)s?
techniques.How
For experienced
programmers, the book demonstrates Python's breadth of
Are you stillcapabilities
seeingand
%(Dating)s?
shows the ways that Python interfaces with Java APIs for professional
application development.

How is work at the office?


I bet it is hard
being a %(Occupation)s.
Python Programming
with the Java(TM) Class Libraries: A Tutorial for Building Web
I know I could
not do Applications
it.
and Enterprise
with Jython covers important topics such as:
"""
Fundamental
including
statements,
Then you print out each dictionary
usingprogramming
the dialog concepts,
format string
with the
% format expressions,
string operator.
interpreters, and compilers

print dialog % Ross


Python basics, including operators, string formatting, namespaces, classes, errors,
print dialog % Chandler
and exceptions
print dialog % Monica
The output is

Object-oriented programming concepts

Hi Ross,

File input/output

Python's
functions
How are you doing?
Howintrinsic
is Rachael?
Are you still seeing Rachael?

Formatting, parsing, and manipulating strings

How is work at the


office?
Interfacing with the Java APIs and working with Java Streams
I bet it is hard being a Scientist Museum Dude.
I know I could not
doPython
it.and Java Swing to create GUIs
Using
Hi Chandler,
Working with SQL and JDBC(TM)
How are you doing? How is Monica?
Python and
Java applets
Are you still seeing
Monica?
In addition,
the book contains instructions for downloading and installing the Python
How is work at
the office?
language
and
the Java
Development Kit (JDK). Terminology, definitions, explanations,
I bet it is hard being
a Buyer.
and
numerous
code
samples
make this book a useful learning experience.
I know I could not do it.
Whether you are a sophisticated computer user new to programming or a serious

Hi Monica,
application developer, Python Programming with the Java(TM) Class Libraries will
How are you doing? How is Chandler?
give you insight into the power of Python and the know-how to put it to work.
Are you still seeing Chandler?

777

How is work at the office?


I bet it is hard being a Chef.
I know I could not do it.

Python Programming with the Java Class Libraries: A Tutorial for Building

%(Income)d is aWeb
useful,
flexible
feature.
You just sawwith
howJython
much time it can save you in writing form letters.
and
Enterprise
Applications
Imagine what it can By
doRichard
for writing
reports.
Hightower

Summary

Publisher: Addison Wesley


Pub Date: June 28, 2002

0-201-61616-5
StringTable
formatting
is the wayISBN:
we organize
instructions so that Python can understand how to incorporate data in
of

Pages:
the creation
of strings. How strings640
are formatted determines the presentation of this data. The basis of string
Contents
formatting is its use of the formatting directives.
Characterized by ease of use, richness of expression, and concise syntax, Python has
remained
a premier
language
for more than
a decade,
by,is
Logical operators (and
,or,not
) returnprogramming
true or false values.
Comparison
operators
(in,and
notis used
in,is
novices
and
professionals
alike.
In
particular,
its
close
relationship
to
Java(TM)
not,==,!=,<>,>,>=,<,<=) compare two valuesis one value greater than another, or is one valuemakes
not
the two languages,
when 1used
combination,
ideal for Web and distributed enterprise
equal to another? Comparisons
always return
for in
true
and 0 for false.
application development.
Any value in Python equates to a Boolean true or false. A false can be equal to none, a zero of numeric type ( 0,
tutorial
begins
with
some of the
basics
Python
programming.
Using
0l,0.0), an empty This
sequence
( ''
,(),[]
), orcoverage
an emptyofdictionary
({}
). All of
other
values
are considered
true.
plenty of skill-building exercises and interactive programming sessions, this book will
Sequences, tuples, lists,
strings
be added or multiplied
a numeric type
the addition
and
helpand
those
new can
to programming
develop anby
understanding
of with
concepts
and practical
multiplication operators
(+,*), respectively.
Strings
can be formatted
withdemonstrates
tuples and dictionaries
using the
techniques.
For experienced
programmers,
the book
Python's breadth
of
format directives %i,
%d, %f
, and
%e.the
Formatting
caninterfaces
be used with
capabilities
and
shows
ways thatflags
Python
withthese
Javadirectives.
APIs for professional
application development.

CONTENTS

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
Object-oriented programming concepts
File input/output
Python's intrinsic functions
Formatting, parsing, and manipulating strings
Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs
Working with SQL and JDBC(TM)
Python and Java applets
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
CONTENTS
Web and Enterprise Applications with Jython
By Richard Hightower

Chapter 4. Control
Flow
Publisher: Addison Wesley
Pub Date: June 28, 2002

The if Statement ISBN: 0-201-61616-5


Table of
The while Statement
Pages: 640
Contents
The for Statement
Characterized
Putting It All
Together by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
Summary

novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
Terms in This Chapter
application development.
This
tutorial begins with coverage of someKey/value
of the basics
Argument
pairof Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
breakthose
and continue
statements develop anLooping
help
new to programming
understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
Built-in (intrinsic)
functions
capabilities
and shows
the ways that PythonMethod
interfaces with Java APIs for professional
application development.
Compound statem ent
Modulus operator
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
else/elif
clause Applications with Jython covers
Nested
dictionary
and
Enterprise
important
topics such as:
for loop
Sequence
Fundamental programming concepts, including statements, expressions,
Function
String format operator
interpreters, and compilers
if, for, Python
and while
statements
Subordinate
statement
basics,
including operators, string
formatting,
namespaces, classes, errors,

and exceptions
Iteration

Suite

Object-oriented programming concepts


Control flow instructs Python, on the basis of certain conditions, to execute particular statements and not others.
It also allows repeated execution
of statements until some conditions are met and permits branching of
File input/output
conditional execution. In this chapter, we'll cover the if,while, and for compound statements, all of which
control statement executionPython's
in Python.
intrinsic functions
Formatting, parsing, and manipulating strings
The if Statement
Interfacing with the Java APIs and working with Java Streams
Theif statement conditionally executes a statement's suite. One form is shown here:
Using Python and Java Swing to create GUIs

if(expression):
suite
Working with SQL and JDBC(TM)
Python has to determine whether
expression
Pythonif
and's Java
appletsis true or false. If the expression is true, Python executes the
suite; if not, it doesn't. As we discussed in Chapter 3, Python doesn't have a Boolean (true/false) type. Instead,
In addition,
the book
contains
for zero,
downloading
andsequence,
installingand
thethe
Python
it uses any numeric value
other than
zero to
indicateinstructions
true and uses
any empty
value
language
and the Java
Development
Kit (JDK).
Terminology,
definitions,
explanations,
None to indicate false.
For example,
the following
will print
"hello"
because the
expression
contains a
and numerous code samples make this book a useful learning experience.
value of 1.

Whether you are a sophisticated computer user new to programming or a serious


>>> # 1 is true
>>> if(1): application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.
...
print("hello")
...
hello

777

Notice that the subordinate statement, print, is indented, which shows that it's part of the suite associated with

if. In interactive mode,


you Programming
indent an if suite
with
Tab key.
The
... prompt
indicates
subordinate
Python
with
thethe
Java
Class
Libraries:
A Tutorial
fora Building
statement.

Web and Enterprise Applications with Jython


By Richard Hightower

The next four statements further illustrate how Python determines whether or not to execute an if statement
based on the value in the
expression.
Publisher:
Addison Wesley
Pub Date: June 28, 2002
>>> #0 is an integer
and 0 means false
ISBN: 0-201-61616-5
>>> Table
if (0):
of
Pages: 640
... Contents
print("goodbye")
...

>>>
>>>
...
...

Characterized by ease of use, richness of expression, and concise syntax, Python has
programming
decade, and is used by
#3.3 is aremained
floata premier
and not
equal language
to 0 for
so more
it than
is atrue
novices
and
professionals
alike.
In
particular,
its
close
relationship
to Java(TM) makes
if (3.3):
the
two
languages,
when
used
in
combination,
ideal
for
Web
and
distributed
enterprise
print("hello")
application development.
This tutorial begins with coverage of some of the basics of Python programming. Using

hello
plenty of skill-building exercises and interactive programming sessions, this book will
>>> #0.00 is equal to 0, which means false
help those new to programming develop an understanding of concepts and practical
>>> if (0.000):
techniques. For experienced programmers, the book demonstrates Python's breadth of
...
print("goodbye")
capabilities and shows the ways that Python interfaces with Java APIs for professional
...
application development.

>>> if(0.000000000000000000001):
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
...
print("hello")
and Enterprise Applications with Jython covers important topics such as:
...
hello
Fundamental programming concepts, including statements, expressions,

if can determine if a list isinterpreters,


empty, as seen
in the checkSeq() function shown in the first example below.
and compilers
The result is shown in the second example. Remember, an empty list indicates false.
Python basics, including operators, string formatting, namespaces, classes, errors,
>>> def checkSeq(seq):
and exceptions

...
...
...
...
...

if (seq):
Object-oriented
concepts
print
"has programming
item"
else :
File input/output
print
"empty"
Python's intrinsic functions

>>> non_empty_list
= [1,2,3]
Formatting, parsing, and manipulating strings
>>> empty_list = []
Interfacing with the Java APIs and working with Java Streams

>>> checkSeq(empty_list)
empty
Using Python and Java Swing to create GUIs
>>> checkSeq(non_empty_list)
Working with SQL and JDBC(TM)
has item
Pythonexpressions
and Java applets
Typically,if statements contain
that use comparison and logical operators. To illustrate, let's say
that a woman is looking for her perfect mantall, dark, and handsome; the strong, quiet type between the ages
In addition,
bookher
contains
instructions
for downloading and installing the Python
of 27 and 35. In Python,
she can the
express
preferences
like this:
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
numerous
samples make
booktalksAlot
a useful learningand
experience.
if (tall and and
dark
and code
handsome
andthisnot
(age>27) and (age<35)):

#(same line)
Whether you are a sophisticated computer user new to programming or a serious
print ("Hi handsome")
application developer, Python Programming with the Java(TM) Class Libraries will
youthat
insight
power
of Pythontoand
know-how
to putmeet
it tothe
work.
Here's an interactivegive
session
usesinto
the the
above
information
helpthe
our
female friend
man of her
dreams:

>>> tall = 1
>>> dark = 1

777

>>> handsome Python


= 1 Programming with the Java Class Libraries: A Tutorial for Building
>>> talksAlotWeb
= and
0 Enterprise Applications with Jython
>>> age = 32 ByRichard Hightower
>>> if (tall and dark and handsome and not talksAlot and (age>27) and (age<35
...
print("Hi
handsome")
Publisher:
Addison Wesley
...
Pub Date: June 28, 2002
Hi handsome
ISBN: 0-201-61616-5

Table of

Pages: 640

At theContents
beginning of the chapter, we saw the basic form of if. We will look at two other forms, containing
else and elif clauses, respectively, in the two sections that follow.
Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
else
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
Theelse form appears
as
application
development.

if(expression):
This tutorial begins with coverage of some of the basics of Python programming. Using
suite plenty
1 of skill-building exercises and interactive programming sessions, this book will
else:
help those new to programming develop an understanding of concepts and practical
suite techniques.
2
For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
Before it can executeapplication
this expression,
Python must determine, as usual, whether it's true. If so, Python executes
development.
the first suite; if not ("else"), it executes the second suite. The following simple greet() function illustrates
theif:else form:Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

>>> def greet(name, sex):


...
#if female print Ms.
programming concepts, including statements, expressions,
...
if(sex ==Fundamental
"female"):
interpreters,
and compilers
...
print
("Hello
Ms. " + name)
...
#if male print Mr.
Python basics, including operators, string formatting, namespaces, classes, errors,
...
else:
and exceptions
...
print("Hello
Mr. " + name)
...
Object-oriented programming concepts

>>>
# greet James
who is a male
File input/output
>>> greet("James Agular", "male")
Hello Mr. James Agular
Python's intrinsic functions
>>>
# greet Jane
who parsing,
is a and
female
Formatting,
manipulating strings
>>> greet("Jane Doe", "female")
Interfacing with the Java APIs and working with Java Streams
Hello Ms. Jane Doe
Usingsex
Python
Java Swingistofalse,
createwhich
GUIsmeans that the first time we invoke
We can see that the expression
==and
"female"
greet() Python will execute the second suite and print ("Hello Mr. " + name"). However, the
Working, with
SQL and JDBC(TM)
second time we invoke greet()
the expression
sex = = "female" is true, so Python executes the first
suite.
Python and Java applets

Separating Suites
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous
samples
this booksuitessemicolons
a useful learning experience.
These two if statements
illustrate code
the two
styles make
of separating
and indenting:
Whether you are a sophisticated computer user new to programming or a serious
>>> sex = "female"
application
developer, Python Programming with the Java(TM) Class Libraries will
>>> name = "Fran
Dresser"
give you insight into the power of Python and the know-how to put it to work.

>>> #First if statement


>>> if (sex == "female"):print("Hello,"); print("It's good to see you Ms." +
...
Hello,

777

It's good to Python


see you
Ms.Fran
Dresser
Programming
with
the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython

>>> #second if
statement
By Richard
Hightower
>>> if (sex == "female"):
...
print("Hello,")
Publisher: Addison Wesley
...
print ("It's
good
Pub Date: June
28,to
2002see you Ms. " + name)
...
ISBN: 0-201-61616-5
Table of
Hello,

Pages: 640
It'sContents
good to see you Ms. Fran Dresser
Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
two appears
languages,
Theelif ("else-if")the
clause
as when used in combination, ideal for Web and distributed enterprise
application development.

elif

if(expression 1):
suite This
1 tutorial begins with coverage of some of the basics of Python programming. Using
plenty
of skill-building exercises and interactive programming sessions, this book will
elif(expression 2):
help
those
new to programming develop an understanding of concepts and practical
suite 2
techniques.
For experienced programmers, the book demonstrates Python's breadth of
else:
capabilities
and shows the ways that Python interfaces with Java APIs for professional
suite 3
application development.
which Python translates as "If the expression is true, execute the corresponding suite; else, if the next expression
Python Programming
with
Class
Libraries:
A Tutorial
for Building Web
is true, execute the corresponding
suite," and
sothe
on.Java(TM)
The else
clause
here is actually
optional.
and Enterprise Applications with Jython covers important topics such as:
Here's an example of elif based on the previous interactive greet() session:
Fundamental
>>> def greet(name,
sex):programming concepts, including statements, expressions,
interpreters,
and compilers
...
if( sex ==
"female"):
...
print("Hello Ms. " + name)
including operators, string formatting, namespaces, classes, errors,
...
elif( sexPython
== basics,
"male"):
and
exceptions
...
print ("Hello Mr. " + name)
...
elif( sex == "undeclared"):
Object-oriented programming concepts
...
print("Hello " + name)
...
else:
File input/output
...
print("Hello " + name)
...
Python's intrinsic functions
As you can see from the added
clauses,parsing,
there can
bemanipulating
multiple elif
s in an if statement. However, the if
Formatting,
and
strings
clause stays the same and uses the same expression. The second clause, ...elif (sex = =
"male"): , checks to seeInterfacing
if the sex is
male
so, prints
out "Hello
Mr"
. The third clause,
with
theand,
JavaifAPIs
and working
with Java
Streams
...elif(sex == "undeclared"):, checks to see if the sex has even been declared; if not, it prints a
Using Python and Java Swing to create GUIs
simple "Hello".

Working
with SQL
and the
JDBC(TM)
So, if we invoke the greet()
function
like this,
second suite, associated with the first elif clause, is
executed:
Python and Java applets

>>> greet("Bob Dole", "male")


Hello Mr. BobIn addition,
Dole the book contains instructions for downloading and installing the Python

language and the Java Development Kit (JDK). Terminology, definitions, explanations,
andthis,
numerous
samples
makewith
this the
book
useful learning
experience.
But if we invoke it like
the firstcode
suite,
associated
ifa clause,
is executed:
Whether
you are a sophisticated
>>> greet("Jane
Smith",
"female")computer user new to programming or a serious
application
Hello Ms. Jane
Smithdeveloper, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.
Similarly, if we invoke the greet() function like this, the third suite, associated with the second elif
clause, is executed:

777

>>> greet("Jean Costello", "undeclared")

Hello Jean Costello


Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython

However, if we invoke
it like this,
the else clause's suite is executed:
By Richard
Hightower

>>> greet("Jean Smith", "")


Publisher: Addison Wesley
Hello Jean Smith
Pub Date: June 28, 2002

ISBN:which
0-201-61616-5
NoticeTable
that else
is the default,
means that its suite is executed if none of the other clauses' expressions
of

Pages:
640
turn out
to be true.
Contents

To sum up, the if statement


is used
conditional
execution
of suites. As
statement,
consists of
Characterized
byfor
ease
of use, richness
of expression,
anda compound
concise syntax,
Pythonit has
theif,elif, and else
clauses,
each of
which has anlanguage
associated
evaluating
remained
a premier
programming
forsuite.
moreBy
than
a decade,the
andexpression
is used byin each
novices
and
professionals
alike. In which
particular,
its close
to Java(TM)
makesthe
clause until one is found
to be
true,
Python determines
clause's
suite relationship
to execute. As
soon as it finds
right one, it stops evaluating.
If all of thewhen
expressions
found to be
false,
executes
the else
clause's
the two languages,
used in are
combination,
ideal
forPython
Web and
distributed
enterprise
suite. If else isn't there
and alldevelopment.
other clause's expressions are false, no suite is executed.
application

This tutorial begins with coverage of some of the basics of Python programming. Using

The while Statement


plenty of skill-building exercises and interactive programming sessions, this book will

help those new to programming develop an understanding of concepts and practical


Thewhile statement
repetitively
executes
a suiteprogrammers,
until a condition
is met.
Its basic form
is
techniques.
For
experienced
the book
demonstrates
Python's
breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
while( expression
):development.
application

suite

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
which you can thinkand
of inEnterprise
English asApplications
"While the expression
execute
the such
suite as:
repeatedly." Python
with Jythonremains
covers true,
important
topics
carries out this instruction by returning to the top of the statement to check if the expression is still true; if so, it
executes the suite a second time and once again returns to the top (this is referred to as looping), repeating this
programming
concepts,Python
including
statements,
process until the expressionFundamental
becomes false.
Once that happens,
stops
executing,expressions,
and the while
interpreters,
statement's execution comes
to a halt. and compilers
Python is
basics,
including
string formatting,
namespaces,
classes,
One use of the while statement
to remove
itemsoperators,
from a listfor
example, every
occurrence
of theerrors,
string
cat from the list pets. and exceptions
Object-oriented
programming"fish",
concepts "cat", "cat", "cat"] #same line
>>> pets = ["cat",
"dog", "bird",
Fileainput/output
We know from Chapter 2 that
list has a count() method that returns the count of an item in the list and a
remove() method that removes the first occurrence of an item. Our goal is to remove the cat string from the
intrinsic
pet list while its count is Python's
greater than
zero. functions
We express this in Python as
Formatting, parsing,
and manipulating
>>> pets = ["cat","dog",
"bird",
"fish",strings
"cat", "cat", "cat"] #same line
>>> while(pets.count("cat") > 0):
Interfacing with the Java APIs and working with Java Streams
...
pets.remove("cat")
...
print (pets)
Using Python and Java Swing to create GUIs
...
Working with SQL and JDBC(TM)
To demonstrate what happens at each iteration of the loop, we print each iteration's resulting pets list to get the
following output:
Python and Java applets

['dog', 'bird',
'fish',
'cat',
'cat', 'cat']
In addition,
the book
contains instructions
for downloading and installing the Python
['dog', 'bird',
'fish',
'cat',
'cat']
language and the Java Development
Kit (JDK). Terminology, definitions, explanations,
['dog', 'bird',
'fish',
and numerous
code'cat']
samples make this book a useful learning experience.
The first cat was removed
theare
first
execution of the
while
statement,
but there are still
occurrences
Whetheron
you
a sophisticated
computer
user
new to programming
or a three
serious
ofcat remaining, soapplication
the while
loop's
suite
is
executed
three
more
times.
developer, Python Programming with the Java(TM) Class Libraries will

give you insight into the power of Python and the know-how to put it to work.

break

777

Thebreak statement allows you to break out of a while statement before it loops back to the top. This is
useful, for example, when inputting several name/phone-number pairs in an address book application. The

following statement Python


uses the Programming
raw_input()
built-in
function
(which
reads a line
from thefor
console).
An empty
with
the Java
Class
Libraries:
A Tutorial
Building
string indicates that inputting
complete: Applications with Jython
Web andisEnterprise
By Richard Hightower

>>> while(1):
...
name = Publisher:
raw_input("Enter
in the name: ")
Addison Wesley
...
if(namePub==
""):
Date: June 28, 2002
...
break
ISBN: 0-201-61616-5
... Table ofphone_number = raw_input("Enter in the phone number: ")
Pages: 640
... Contents
#Do something useful with the name and phone_number
Characterized
by ease
of in
use,
richness
expression,
syntax,
Python has
Notice the while(1):
expression,
which
effect
tells of
Python
to loopand
the concise
suite forever.
However,
the
remained
a
premier
programming
language
for
more
than
a
decade,
and
is
break statement stops this "infinite looping" by instructing Python to break out of the loop if used
it hitsby
an empty
novices
and professionals
alike. by
In particular,
name string. Here's the
interactive
session, followed
its output: its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application
development.
...
if(name
== ""):

...
Enter
Enter
Enter
Enter
Enter
>>>

in
in
in
in
in

break
tutorialRick
beginsHightower
with coverage of some of the basics of Python programming. Using
the This
name:
plenty
of
skill-building
and interactive programming sessions, this book will
the phone number: exercises
555-5555
help
those
new
to
programming
develop
an understanding of concepts and practical
the name: Adam Carr
techniques.
For
experienced
programmers,
the book demonstrates Python's breadth of
the phone number: 555-6666
capabilities
and
shows
the
ways
that
Python
interfaces with Java APIs for professional
the name:
application development.

Python
Class
Libraries:
A Tutorial
for Building
As you can see, the last
timeProgramming
we're asked towith
enterthea Java(TM)
name, we hit
Enter
so that the
string returned
from Web
and
Enterprise
Applications
with
Jython
covers
important
topics
such
as:
raw_input is empty.

continue

Fundamental programming concepts, including statements, expressions,


interpreters, and compilers
Thecontinue statement is similar to the break statement. However, instead of instructing Python to break
Python
including
operators,
formatting,
namespaces,
classes,We'll
errors,
out, it tells it to return to the
top ofbasics,
the while
statement,
thatstring
is, where
the expression
is evaluated.
stick
and
exceptions
with the address book example to illustrate continue , adding the ability to enter an address. If the first line of
the address is empty, we can assume that the user doesn't want to exercise this option, and we go back to the top
Object-oriented programming concepts
of the loop.
File input/output

>>> while (1):


...
name = raw_input("Enter
Python's intrinsic functionsin the name: ")
...
if (name == ""):
...
break
Formatting, parsing, and manipulating strings
...
phone_number = raw_input("Enter in the phone number: ")
...
address_line1
= with
raw_input("Enter
address
Interfacing
the Java APIs and working
with Java line
Streamsone: ")
...
if (address_line1 == ""):
Using Python and Java Swing to create GUIs
...
continue
...
address_line2 = raw_input("Enter address line two: ")
Working =
withraw_input("Enter
SQL and JDBC(TM)
...
address_line3
address line three: ")
...
#Do something useful with the data we just collected
Python and Java applets
...
In addition, the book contains instructions for downloading and installing the Python
As with break,while(1) triggers an infinite loop of the associated suite. Again, the only way to end the
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
loop is via the break statement.
and numerous code samples make this book a useful learning experience.
Since we've added the address option, we test to see if address_line1 is empty. If so, we continue with
Whether you are a sophisticated computer user new to programming or a serious
the next entry, that is, the next iteration of the loop, by adding the following statement:
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight=intoraw_input("Enter
the power of Python and the
know-howline
to put itone:
to work.
...
address_line1
address
")

...
...

if (address_line1 == ""):
continue

777

In English, this says, "Get the first line of a person's address from the user and test to see if it's an empty string. If

so, continue executing


at the Programming
top of the while
statement;
in other
get the
next person's
information."
Python
with
the Java
Classwords,
Libraries:
A Tutorial
for Building
Web and Enterprise Applications with Jython

Below are samples of


output,
in order, from the four iterations of the preceding name/phone-number
Bythe
Richard
Hightower
program.
Publisher: Addison Wesley

Enter in the name: Rick Hightower


Pub Date: June 28, 2002
Enter in the phone
number: 555-5555
ISBN: 0-201-61616-5
Enter
address
line
one: 123 Main St.
Table of

Pages:
640 Tucson, Az
Enter
address line
two:
Contents
Enter address line three: 85226

Characterized by ease of use, richness of expression, and concise syntax, Python has
premierCarr
programming language for more than a decade, and is used by
Enter in the remained
name: aAdam
novices
and
professionals
alike. In particular, its close relationship to Java(TM) makes
Enter in the phone number: 555-6666
the
two
languages,
when
used
in combination, ideal for Web and distributed enterprise
Enter address line one:
application development.

Enter
Enter
Enter
Enter
Enter

in the name: Bob Ninny


This tutorial begins with coverage of some of the basics of Python programming. Using
in the phone number: 555-7777
plenty of skill-building exercises and interactive programming sessions, this book will
address line one: 1234 South Dobson
help those new to programming develop an understanding of concepts and practical
address line two: Mesa, AZ
techniques. For experienced programmers, the book demonstrates Python's breadth of
address line three: 85228
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.

Enter in the name:

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
In the first iteration, we fill in all fields for Rick Hightower, including the optional address fields. In the second,
and Enterprise Applications with Jython covers important topics such as:
we fill in only Adam Carr's name and phone number, and at the first address field, hit Enter. The statement
below instructs Python to return to the top of the while statement to begin executing again, thus skipping the
rest of the statements in while
's suite: programming concepts, including statements, expressions,
Fundamental
interpreters, and compilers

...
...

if (address_line1 == ""):
continue
Python basics, including operators, string formatting, namespaces, classes, errors,

and exceptions
In the third iteration, all of Bob Ninny's fields are filled in. In the fourth iteration, when the program asks us to
enter a name, we hit Enter,Object-oriented
causing raw_input()
to return
an empty string. This means that the following
programming
concepts
statement forces the while loop to terminate:
File input/output

...
...

else

if(name == ""):
Python's intrinsic functions
break
Formatting, parsing, and manipulating strings

Interfacing with the Java APIs and working with Java Streams
Likeif,while can contain an else clause:
Using Python and Java Swing to create GUIs

while (expression):
suite 1 Working with SQL and JDBC(TM)
else:
suite 2 Python and Java applets
In addition,
book contains
installing
thesuite
Python
Likeif'selse,while
'selse the
repeatedly
tests theinstructions
expression.for
If downloading
the expressionand
is true,
the first
is
language
and the
Development
Kitthe
(JDK).
executed. If the expression
is false,
or Java
becomes
false during
loop,Terminology,
else's suitedefinitions,
is executed,explanations,
and the while
and numerous
code samples
make
this book
useful
learning experience.
loop ends. If the executed
suite contains
a break
statement,
thealoop
terminates,
and the else suite is not
executed.
Whether you are a sophisticated computer user new to programming or a serious
developer,
Programming
with the
ClassofLibraries
willprogram
Continuing with ourapplication
address book
example,Python
we'll use
the else clause
to Java(TM)
add the option
quitting the
insightbook
intotothesomeonesay,
power of Python
the know-how
to putwe
it to
by sending an email give
of theyou
address
me.and
Typing
in quit when
getwork.
the name means
that we want to breaknot sendthe email. Entering " " (empty string) means that we want to execute the
statements in the else clause and send the email. Of course, we won't actually send any email, so the
emailData() function is commented out.

777

name = " " Python Programming with the Java Class Libraries: A Tutorial for Building
while (name !=
Web""):
and Enterprise Applications with Jython
name =ByRichard
raw_input("Enter
in the name: ")
Hightower
if (name == ""):
continue
Publisher: Addison Wesley
elif (name
== June
"quit"):
Pub Date:
28, 2002
break
ISBN: 0-201-61616-5
Table phone_number
of
= raw_input("Enter in the phone number: ")

Pages: 640
Contents
address_line1 = raw_input("Enter address line one: ")
if (address_line1
""):
Characterized by ease==
of use,
richness of expression, and concise syntax, Python has
continue
remained a premier programming language for more than a decade, and is used by
address_line2
= raw_input("Enter
line to
two:
") makes
novices and professionals
alike. In particular, address
its close relationship
Java(TM)
address_line3
= raw_input("Enter
line
three: enterprise
")
the two languages,
when used in combination,address
ideal for Web
and distributed
#do something
useful with the addresses
application development.
else:
print("send
email
to Rick")
This tutorialthe
begins
with coverage
of some of the basics of Python programming. Using
#emailAddresses("rick_m_hightower@emailcompany.com")
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
Let's break down thetechniques.
changes made
the program.
For to
experienced
programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
First, if the while clause encounters an empty string for the name variable, it exits the loop.
application development.

while (name != ""):

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
Enterprise
with Jython
important
topics
such as:
If we pass an empty and
string
for nameApplications
, the continue
clausecovers
kicks in,
returning
execution
to the beginning of
thewhile statement. Then the expression in the while clause is evaluated. The empty string there allows the
while loop to terminate gracefully,
as programming
opposed to breaking
out,including
so the else
clause expressions,
is executed.
Fundamental
concepts,
statements,

interpreters, and compilers

elif (name == "quit"):


breakPython basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
Theelif clause in the if statement ensures that, if the name string equals quit, we break out of the loop
(we terminate ungracefully).
So the else clause
isn't executed,
Object-oriented
programming
conceptsallowing us to quit without sending the email,
and I don't get my address list.
File input/output

else:

print("send
theintrinsic
email
to Rick")
Python's
functions
#emailAddresses("rick_m_hightower@emailcompany.com")
Formatting, parsing, and manipulating strings
Here we've added the else clause to the while loop with the same indentation as that of the while clause
Interfacing
with
Java APIs and working with Java Streams
of the while statement. Try
executing
thisthe
script.
Using Python and Java Swing to create GUIs

The for Statement

Working with SQL and JDBC(TM)


Thefor statement repeatedly executes a suite of statements as it iterates through the items in a sequence. It
Python and Java applets
appears as
In addition, the:book contains instructions for downloading and installing the Python
for item in sequence
suite language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
The expression should be a valid sequence (a tuple, string, or list). At the beginning of each iteration, the next
youtoare
sophisticated
computer
to programming
or a serious
item in the sequenceWhether
is assigned
thea item
variable,
and the user
suitenew
is executed.
This continues
until all items
application
developer,
Python
Programming
with
the
Java(TM)
Class
Libraries will
have been dealt with.
give you insight into the power of Python and the know-how to put it to work.
To illustrate for, let's say that we have a list of email addresses for a monthly newsletter.

777

>>> email_list = ["rick_m_hightower@emailcompany.com",


"adam_s_carr@hottermail.com", "bill_g_smith@hottestmail.com"]

>>>
Python Programming with the Java Class Libraries: A Tutorial for Building
>>> for address
in Enterprise
email_list:
Web and
Applications with Jython
...
printByRichard
("Sending
email to " + address)
Hightower
...
# sendEmail(address, "Nothing new here")
Sending email to
rick_m_hightower@emailcompany.com
Publisher:
Addison Wesley
Sending email to
adam_s_carr@hottermail.com
Pub Date: June 28, 2002
Sending email to ISBN:
bill_g_smith@hottestmail.com
0-201-61616-5
>>> Table of
Pages: 640
Contents

Like the while loop, the for loop uses an else clausewhen there are no more items in the list, else is
Characterized by ease of use, richness of expression, and concise syntax, Python has
executed. The break and continue statements work in for as they do in while.
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
The range() Function
and for
Loops
the two languages,
when
used in combination, ideal for Web and distributed enterprise
application development.
Thefor loop in Python can be used similarly to the for loop in Java and C with the range() function,
begins
withvalues.
coverage
some ofexample
the basics
Python
programming.
Using of
whose purpose is to This
returntutorial
a list of
numeric
Theofsimplest
is aoflist
of 1 through
9 in increments
plenty
of
skill-building
exercises
and
interactive
programming
sessions,
this
book
will
1.
help those new to programming develop an understanding of concepts and practical
>>> range(1,10)
techniques. For experienced programmers, the book demonstrates Python's breadth of
[1, 2, 3, 4, capabilities
5, 6, 7,
9]the ways that Python interfaces with Java APIs for professional
and 8,
shows
application development.
Other examples of range() follow. Respectively, they illustrate 1 through 20 by increments of 2; 0 through
100 by increments ofPython
10; -100
through 200with
by increments
of 30;
andLibraries:
100 through
-100 byfor
increments
20.
Programming
the Java(TM)
Class
A Tutorial
Buildingof
Web
and Enterprise Applications with Jython covers important topics such as:

>>> range(1, 20, 2)


[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
Fundamental programming concepts, including statements, expressions,
interpreters,
>>> range (0, 100,
10) and compilers

[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
Python basics, including operators, string formatting, namespaces, classes, errors,
exceptions
>>> range (-100, and
200,
30)

[-100, -70, -40, -10, 20, 50, 80, 110, 140, 170]
Object-oriented programming concepts

>>> range (100, -100,


-20)
File input/output
[100, 80, 60, 40, 20, 0, -20, -40, -60, -80]
Python's intrinsic functions
To create a loop that iterates from 0 through 100 by increments of 10, we enter
Formatting, parsing, and manipulating strings

>>> for x in range(0, 100, 10):


...
print("x Interfacing
equals with
" +the`x`)
Java APIs and working with Java Streams
...
Using Python and Java Swing to create GUIs
which outputs

Working with SQL and JDBC(TM)

x
x
x
x
x
x
x
x
x
x

equals
equals
equals
equals
equals
equals
equals
equals
equals
equals

0
10
20
30
40
50
60
70
80
90

Python and Java applets


In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

Or we can iterate backward from 100 to 0 by decrements of 10 by entering

777

>>> for x in range (100, 0, -10):

...
...

print("x
" + with
`x`)
Pythonequals
Programming
the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

which outputs

x
x
x
x
x
x
x
x
x
x

Publisher: Addison Wesley

equals 100
Pub Date: June 28, 2002
equals 90
ISBN: 0-201-61616-5
equals
Table of 80

Pages:
640
equals
Contents70
equals 60
equals 50 Characterized by ease of use, richness of expression, and concise syntax, Python has
equals 40 remained a premier programming language for more than a decade, and is used by
equals 30 novices and professionals alike. In particular, its close relationship to Java(TM) makes
equals 20 the two languages, when used in combination, ideal for Web and distributed enterprise
equals 10 application development.

This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
xrange() is nearly
identical to
, except
that it doesn't
create
individual items
in a breadth
range until
techniques.
Forrange()
experienced
programmers,
the book
demonstrates
Python's
of
requested to do so, which
makesand
it more
efficient
thanthat
range()
for largewith
ranges.
of
capabilities
shows
the ways
Python interfaces
JavaHere's
APIs an
forexample
professional
xrange() , calledapplication
xrange.py, followed
by its output:
development.
xrange()

print ("This Python


for Programming
loop useswith
xrange,
which
in the range"
the Java(TM)
Class lazily
Libraries: Acreates
Tutorial formembers
Building Web
for x in xrange
(-1000000000,
1000000000):
and Enterprise Applications with Jython covers important topics such as:
if( (x % 100000) == 0): print (`x`)
Fundamental programming
if (x == -999900000):
break concepts, including statements, expressions,
compilers C")
print ("Get readyinterpreters,
to hitand
control
print ("This for loop uses range")
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
for x in range (-1000000000,
1000000000):

if( (x % 100000) == 0): print (`x`)


Object-oriented programming
if (x == -999900000):
break concepts
File input/output

>>> import xrange


This for loop uses
xrange,
which lazily creates members in the range
Python's
intrinsic functions
-1000000000
-999900000
Formatting, parsing, and manipulating strings
Get ready to hit control C
Interfacing
This for loop uses
rangewith the Java APIs and working with Java Streams
Out of Memory
Using Python and Java Swing to create GUIs
Notice that when we try to create the second range we run out of memory. In essence, the second range()
Working
withintegers,
SQL and
JDBC(TM)
tries to create a list containing
2 billion
each
32 bits wide (4 bytes). For this we need a computer with 8
billion bytes, or 8 gigabytes, of memory.
Python and Java applets
addition, the book contains instructions for downloading and installing the Python
Putting It AllInTogether
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
anda numerous
code
samples
makewe've
this book
a useful
learning
experience.
Now it's time to create
program that
uses
everything
learned
so far.
This program
will generate a list of
house prices and find their average (mean, mode, and median) and range. The following sections will describe
Whether you are a sophisticated computer user new to programming or a serious
each function in turn.
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

getRange()

777

getRange() iterates through a set of numbers passed to it and calculates the minimum and maximum values.
It then returns these values and their range in a tuple.

Programming with the Java Class Libraries: A Tutorial for Building


def getRange Python
(nums):
and Enterprise Applications with Jython
min = Web
300000000
Richard Hightower
max = By
-300000000
for item in nums:
Addison
Wesley
if (itemPublisher:
> max):
max
= item
June 28,
if (itemPub<Date:
min):
min2002
= item
Table of

ISBN: 0-201-61616-5

return
(min, max,Pages:
max-min)
640
Contents

FirstgetRange()Characterized
declares two by
variables,
and maxof. The
min variable
refers syntax,
to a veryPython
large number,
so
ease of min
use, richness
expression,
and concise
has
the first item extracted
from the
list is less
than that number
and for
is assigned
theamin
value.
maxbyvariable
remained
a premier
programming
language
more than
decade,
andThe
is used
contains a negative number,
so the
first item extracted
be moreitsthan
therelationship
large negative
value andmakes
is assigned
novices and
professionals
alike. Inwill
particular,
close
to Java(TM)
to the max variable. the two languages, when used in combination, ideal for Web and distributed enterprise
application development.

This tutorial begins with coverage of some of the basics of Python programming. Using
Making
getRange()
More
Efficient
plenty
of skill-building
exercises and interactive
programming
sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques.
For experienced
programmers,
the book
Python's
breadth
ThegetRange()
example
will work only
if the numbers
passeddemonstrates
to it are in the
range of
min of
capabilities
and
shows
the
ways
that
Python
interfaces
with
Java
APIs
for
professional
andmax. To make it more general purpose, we can use either of the following:
application development.

from java.lang import Double


Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise
Applications
with Jython covers important topics such as:
from java.lang
import
Double
Fundamental programming concepts, including statements, expressions,
and then either of these:
interpreters, and compilers

min
max
min
max

=
=
=
=

Double.MAX_VALUE
Python basics, including operators, string formatting, namespaces, classes, errors,
Double.MIN_VALUE
and exceptions
Integer.MAX_VALUE
Integer.MIN_VALUE
Object-oriented programming concepts

File input/output
This will make the function
work well with Integer or Double types. The question is how
well it will work with Long types. We'll have our answer shortly.
Python's intrinsic functions
To figure min and max,getRange()
iterates
the nums
sequence.
Formatting, parsing,
andthrough
manipulating
strings

for item in nums:Interfacing with the Java APIs and working with Java Streams
if (item > max): max = item
Python
and=Java
Swing to create GUIs
if (item < Using
min):
min
item
with SQL
anditem's
JDBC(TM)
The expression item > Working
max determines
if the
value is greater than max. If so, max is assigned to it,
as expressed by this compound statement:
Python and Java applets

if (item > max): max = item

In addition, the book contains instructions for downloading and installing the Python
language
and theindicates
Java Development
Kitvalue
(JDK).
Terminology,
explanations,
The following compound
statement
that the item's
is less
than min,definitions,
so it's assigned
to min:
and numerous code samples make this book a useful learning experience.

if (item < min): min = item


Whether you are a sophisticated computer user new to programming or a serious
When the loop stopsapplication
iterating through
the values,
returns
min,maxClass
, and max-min
(range).
developer,
PythongetRange()
Programming with
the Java(TM)
Libraries will
give you insight into the power of Python and the know-how to put it to work.

return (min, max, max-min)

777

The approach just described is a simple one, but it has a flaw. It works only if the numbers passed to
xrange() are within max-min. The solution is the nums variable, which is a sequence with an intrinsic

operation (otherwisePython
known as
a built-in function)
for finding
min and
max in Aa list.
numsforis Building
an improvement
Programming
with the
Java Class
Libraries:
Tutorial
overgetRange()Web
because
much shorter
and can work
all numeric types as well as all Longs,
and it's
Enterprise
Applications
withwith
Jython
Floats, and Double
s at their
maximum range of precision. With nums there's no for loop and no figuring
By Richard
Hightower
out what max and min should be initialized to (that is, given a default value).
Publisher: Addison Wesley

Here's an example of nums:

Pub Date: June 28, 2002

ISBN: 0-201-61616-5
def Table
getRange2
(nums):
of

Pages:
640
return (min(nums),
max(nums), max(nums)-min(nums))
Contents

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
ThegetMean() function
out the
mean
number sequence.
through
the sequence,
adding
the two figures
languages,
when
usedofina combination,
ideal Itforiterates
Web and
distributed
enterprise
all of the values together
and storing
them in sum. It then figures out the mean by dividing sum by the sequence
application
development.
length.
This tutorial begins with coverage of some of the basics of Python programming. Using
In the following getMean()
example, notice
the use
the sample
argument, sessions,
the for this
loop,
the if
plenty of skill-building
exercises
andofinteractive
programming
book
willand
else clauses, and the
built-in
function (which
determines
the length of
sequence).
helplen()
those new
to programming
develop
an understanding
of aconcepts
and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
def getMean (nums,
sample):
capabilities and shows the ways that Python interfaces with Java APIs for professional
"""
application development.

getMean()

DefinePython
mean
that finds
types
of
mean,A Tutorial for Building Web
Programming
with thetwo
Java(TM)
Class
Libraries:
namely:
population
meanwith
and
sample
mean topics such as:
and Enterprise
Applications
Jython
covers important
"""
programming
concepts,
sum Fundamental
= 0.0
# holds
the including
value statements,
of sum expressions,
interpreters, and compilers

#
Python#basics,
including
operators, string
namespaces,
classes, errors,
iterate
through
the formatting,
sequence
of
and
exceptions
# numbers and sum them

for x in nums:
Object-oriented programming concepts
sum = sum + x
File input/output

#
# intrinsic
Checkfunctions
to see if this is a sample mean
Python's
if(sample):
average
sum
/ (len(nums)-1)
Formatting,
parsing,=and
manipulating
strings
Interfacing
# with the Java APIs and working with Java Streams

# Else it is a population mean


Using Python and Java Swing to create GUIs
else:
average = sum / len(nums)
Working with SQL and JDBC(TM)
return average
Here's the breakdown.

Python and Java applets

In addition, the book contains instructions for downloading and installing the Python
First we create a variable called sum that holds the sum.
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
sum = 0.0
Whether
you are
a sophisticated
computer
to programming
or a serious
Then we iterate through
the nums
sequence,
accumulating
theuser
valuenew
of the
item x.
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.
for x in nums:

sum = sum + x

777

Next, using the sample argument, we check to see if this is a sample mean. If so, we figure the average by
dividingsum by the number of items in nums less 1, or we divide the sum by the number of items in the nums

sequence.

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

if(sample):
average = sum / (len(nums)-1)
#
Publisher: Addison Wesley
# Else it
is a population mean
Pub Date: June 28, 2002
else:
ISBN: 0-201-61616-5
= sum / len(nums)
Table average
of

Contents

Pages: 640

Finally we return the average.


Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
return average
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
getMode()
application development.
ThegetMode() function
findsbegins
the value
repeatsof
most
often
in abasics
sequence.
First itprogramming.
duplicates theUsing
sequence
This tutorial
withthat
coverage
some
of the
of Python
so it can modify it. Then
it
iterates
through
the
items
in
the
nums
sequence,
counting
occurrences
of
the
plenty of skill-building exercises and interactive programming sessions, this book willcurrent
items with the built-in
count()
Once getMode()
counts an item,ofitconcepts
removesand
it from
the
help
those newmethod.
to programming
develop an understanding
practical
duplicated sequence.techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
In the getMode() example that follows, notice the use of the for and while loops, the if statement, the
application development.
count() method, and the nested for loop.

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web

def getMode (nums):


and Enterprise Applications with Jython covers important topics such as:
"""Find the number that repeats the most. """

Fundamental programming concepts, including statements, expressions,

# interpreters, and compilers


# make a duplicate copy of the nums argument
basics, including operators, string formatting, namespaces, classes, errors,
duplicate Python
= nums[:]
and
exceptions
highest_count = -100
mode = None
Object-oriented programming concepts

#
File input/output
# calculate the highest_count and the mode
for item in
nums:
Python's
intrinsic functions
count
= duplicate.count(item)
Formatting,
parsing, and manipulating strings
if (count == 0): continue
Interfacing with the Java APIs and working with Java Streams

if (count > highest_count):


Using highest_count
Python and Java Swing=tocount
create GUIs
mode = item
Working with SQL and JDBC(TM)

while(duplicate.count(item) > 0):


Python and Java applets
duplicate.remove(item)
In addition, the book contains instructions for downloading and installing the Python

returnlanguage
mode and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Let's break this down.
Whether you are a sophisticated computer user new to programming or a serious
First we duplicate the nums sequence and create a variable to hold highest_count (and assign it a
application developer, Python Programming with the Java(TM) Class Libraries will
negative starting number) and a variable to hold the nums sequence mode.
give you insight into the power of Python and the know-how to put it to work.

duplicate = nums[:]
highest_count = -100
mode = None

777

Next we iterate through


eachProgramming
item in nums and
duplicate
nums
occurrences.
Python
withcount
the Java
Class
Libraries:
A Tutorial for Building
Web and Enterprise Applications with Jython

for item in nums:


By Richard Hightower
count = duplicate.count(item)
Publisher: Addison Wesley
if (countPub==
0): continue
Date: June 28, 2002
ISBN: 0-201-61616-5
As weTable
iterateofthrough the list,
we see if the current count is greater than highest_count. If it is, we

Pages:
640item to mode.
assignContents
it to highest_count and

Characterized by ease of use, richness of expression, and concise syntax, Python has
if (count > highest_count):
remained a premier
programming language for more than a decade, and is used by
highest_count
= count
novices
and
professionals
alike. In particular, its close relationship to Java(TM) makes
mode = item
the two languages, when used in combination, ideal for Web and distributed enterprise
application
development.
Continuing our iteration,
we remove
all occurrences of the item from the duplicate sequence with the following
while statement:
This tutorial begins with coverage of some of the basics of Python programming. Using
while(duplicate.count(item)
> 0):and interactive programming sessions, this book will
plenty of skill-building exercises
duplicate.remove(item)
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
Finally we return mode
.
capabilities
and shows the ways that Python interfaces with Java APIs for professional
application development.

return mode

getMedian()

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

ThegetMedian() function finds the middlemost value once the sequence is sorted. In the following
Fundamental programming concepts, including statements, expressions,
getMedian() example,interpreters,
notice the use of the modulus operator (%), the if statement, the else clause, and
and compilers
the built-in sort() operation.

Python basics, including operators, string formatting, namespaces, classes, errors,

def getMedian (nums):


and exceptions

"Find
the Median
number"
Object-oriented
programming
concepts
# create a duplicate since
File input/output
# we are going to modify it
intrinsic functions
seq Python's
= nums[:]
Formatting,
manipulating
strings
#sortparsing,
the and
list
of numbers

seq.sort()

Interfacing with the Java APIs and working with Java Streams

median
None
toSwing
hold
the GUIs
median value
Using =Python
and#Java
to create
length
= len(seq)
# to hold the length of the seq
Working
with SQL and JDBC(TM)
# and
Check
to see if the length is an even number
Python
Java applets
if ( ( length % 2) == 0):
In addition, the book contains
instructions
downloading
and installing the Python
# since
it isforan
even number
language and the Java #
Development
(JDK).
Terminology,
definitions,
explanations,
add theKittwo
middle
numbers
together
and numerous
code
samples
make
this
book
a
useful
learning
experience.
index = length / 2
median = (seq[index-1] + seq[index]) /2.0

else: Whether you are a sophisticated computer user new to programming or a serious
application developer, #
Python
Programming
Java(TM)
Class Libraries will
since
it is with
an the
odd
number
give you insight into the
power
of
Python
and
the
know-how
to
put
it to work.
# just grab the middle number
index = (length / 2)
median = seq[index]
return median

777

Once again, let's break


it down.
Python
Programming
First

with the Java Class Libraries: A Tutorial for Building


Web and Enterprise Applications with Jython
we duplicate the
sequence
and sort the duplicate (seq).
Bynums
Richard
Hightower

seq.sort()

Publisher: Addison Wesley

Publength%2
Date: June 28,
Then, with the expression
, we2002
check if the length is an even number. (Remember that the modulus
ISBN:
0-201-61616-5
operator
returns
the
remainder.)
If
the
length
is even, the expression length%2 returns zero, and we calculate
Table of

Pages:
640
the median
by adding together the two most central numbers and figuring their average.
Contents

length = len(seq)
Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by

if ( ( lengthnovices
% 2)and==
0):
professionals
alike. In particular, its close relationship to Java(TM) makes
index =thelength
/ 2 when used in combination, ideal for Web and distributed enterprise
two languages,
median application
= (seq[index-1]
development. + seq[index]) /2.0
Thisgrab
tutorial
begins value.
with coverage of some of the basics of Python programming. Using
If the length is odd, we
the middle
plenty of skill-building exercises and interactive programming sessions, this book will
else:
help those new to programming develop an understanding of concepts and practical
index =techniques.
(length
2)
For /
experienced
programmers, the book demonstrates Python's breadth of
median capabilities
= seq[index]
and shows the ways that Python interfaces with Java APIs for professional
application development.
Finally we return the median.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
return medianand Enterprise Applications with Jython covers important topics such as:

reportStatistics()

Fundamental programming concepts, including statements, expressions,


interpreters,
and
reportStatistics()
calls all of
thecompilers
functions implemented in our house prices
examplegetMean(),getMode(),getRange(),getMedian(), and nested dictionariesand
Python basics, including operators, string formatting, namespaces, classes, errors,
stores their return values in two dictionaries, averages and ranges. It puts these dictionaries in another
and exceptions
dictionary called report, which it returns.

Object-oriented programming concepts

def reportStatistics (nums):


# get
central tendencies
File input/output
averages = {
"mean":getMean(nums,0),
Python's intrinsic functions
"median":getMedian(nums),
Formatting, parsing, and manipulating strings
"mode":getMode(nums)
}
Interfacing with the Java APIs and working with Java Streams

# get range
Using Python and Java Swing to create GUIs
range = getRange(nums)
Working with SQL and JDBC(TM)

# put ranges in a dictionary


ranges = { Python and Java applets
"min":range[0],
In"max":range[1],
addition, the book contains instructions for downloading and installing the Python
"range":range[2]
language
and the Java Development Kit (JDK). Terminology, definitions, explanations,
} numerous code samples make this book a useful learning experience.
and
report Whether
= { you are a sophisticated computer user new to programming or a serious
application
developer,
Python Programming with the Java(TM) Class Libraries will
"averages":
averages,
give
you insight into
the power of Python and the know-how to put it to work.
"ranges":
ranges
}

777

return report

Breaking this down, Python


we first Programming
get the averagesmean,
and modeusing
,
with the median,
Java Class
Libraries: AgetMean()
Tutorial for Building
getMedian(), and
getMode()
. Notice
that "mean":getMedian
defines a key/value pair.
Web
and Enterprise
Applications
with Jython
By Richard Hightower

averages = {
"mean":getMean(nums,0),
Publisher: Addison Wesley
"median":getMedian(nums),
Pub Date: June 28, 2002
"mode":getMode(nums)
ISBN: 0-201-61616-5
Table }of

Contents

Pages: 640

Then we get the range parametersmin,max, and max-minfromgetRange(). We use range[0] ,


Characterized
of use,
richnessNotice
of expression,
and concise syntax, defines
Python has
range[1] , and range[2]
in by
theease
returned
sequence.
that "min":range[0]
a key/value
remained
a
premier
programming
language
for
more
than
a
decade,
and
is
used by
pair in the ranges dictionary.
novices and professionals alike. In particular, its close relationship to Java(TM) makes
two languages, when used in combination, ideal for Web and distributed enterprise
# get the
range
application
development.
range = getRange(nums)

# put ranges in a dictionary


ranges = { This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
"min":range[0],
help those new to programming develop an understanding of concepts and practical
"max":range[1],
techniques. For experienced programmers, the book demonstrates Python's breadth of
"range":range[2]
capabilities and shows the ways that Python interfaces with Java APIs for professional
}
application development.
Now we define a dictionary called report that contains the averages and ranges dictionaries.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
report = { and Enterprise Applications with Jython covers important topics such as:

"averages": averages,
"ranges": ranges
Fundamental programming concepts, including statements, expressions,
}
interpreters, and compilers

Lastly we return the report dictionary.


Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
return report

Object-oriented programming concepts


Using reportStatistics()
File input/output
RunReport() uses reportStatistics() to get the report dictionary it needs to print out the
Python's intrinsicexample,
functionsnote the use of the string format operator (%), the %f format
report. In the following runReport()
directive, nested dictionaries, and the use of the format operator with a dictionary.
Formatting, parsing, and manipulating strings

from chap4 import reportStatistics


Interfacing
with the Java
APIs and working
with 200000,
Java Streams65000, 100000]
house_in_awahtukee
= [100000,
120000,
150000,
report = reportStatistics(house_in_awahtukee)
Using Python and Java Swing to create GUIs

range_format = """
Working with SQL and JDBC(TM)
Range:
The least expensive
%(min)20.2f
Pythonhouse
and Javais
applets
The most expensive house is %(max)20.2f
The range of Inhouse
%(range)20.2f
addition,price
the bookis
contains
instructions for downloading and installing the Python
"""
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.

average_format = """
Whether you are a sophisticated computer user new to programming or a serious
Averages:
application
Python Programming with the Java(TM) Class Libraries will
The mean house
pricedeveloper,
is %(mean)20.2f
you insight
into is
the power
of Python and the know-how to put it to work.
The mode for give
house
price
%(mode)20.2f
The median house price is %(median)20.2f
"""

777

print range_format % report["ranges"]

print average_format
% report["averages"]
Python Programming
with the Java Class Libraries: A Tutorial for Building
Here's the output:

Web and Enterprise Applications with Jython


By Richard Hightower

Range:
Publisher: Addison Wesley
The least expensive house is 65000.00
Pub Date: June 28, 2002
The most expensive
house is 200000.00
ISBN: 0-201-61616-5
The Table
range
of
house
price is 135000.00
of

Contents

Pages: 640

Averages:
Characterized
by ease
of use, richness of expression, and concise syntax, Python has
The mean house
price is
122500.00
remained
a
premier
programming
language for more than a decade, and is used by
The mode for house price is 100000.00
novices
and
professionals
alike.
In
particular, its close relationship to Java(TM) makes
The median house price is 110000.00

Summary

the two languages, when used in combination, ideal for Web and distributed enterprise
application development.

This tutorial begins with coverage of some of the basics of Python programming. Using
of skill-building
exercises and interactive
programming
sessions,
this book will
Control flow allows plenty
programs
to execute nonsequentially
using the if
,while, and
for compound
help
those
new
to
programming
develop
an
understanding
of
concepts
and
practical
statements.if conditionally executes a statement, while executes a statement while a condition
is true, and
techniques.
For
experienced
programmers,
the
book
demonstrates
Python's
of is
for iterates through a sequence. All three can contain else clauses that execute when the ifbreadth
condition
capabilities
and
shows
the
ways
that
Python
interfaces
with
Java
APIs
for
professional
false, when it becomes false, or when the items in a list are or become empty, respectively.
application development.
As compound statements, if,while, and for contain clauses. Clauses contain suites and control their
Python
Programming
withclauses;
the Java(TM)
Libraries:
A Tutorial
for clauses;
Buildingand
Webfor
execution.if contains
if,elif
, and else
whileClass
contains
while
and else
and
Enterprise
Applications
with
Jython
covers
important
topics
such
as:
containsfor and else clauses. Within the while and for statements, break and continue , as their
names imply, break out of a loop and continue a loop from the top.
Fundamental
programming
concepts, including
statements,
expressions,
Specific to the for statement
are the range()
and xRange()
functions.
range()
returns a list of
interpreters,
numbers;xRange() returns
a numberand
in acompilers
range only when requested to do so.
Python basics, including operators, string formatting, namespaces, classes, errors,
We created a sample application to compute range, mean, mode, and median for a group of house prices. The
and exceptions
application highlighted the following key concepts from Chapters 1 through 4:
Object-oriented programming concepts

for loop
while loop

File input/output
Python's intrinsic functions

if statement

Formatting, parsing, and manipulating strings


if and else clauses
Interfacing with the Java APIs and working with Java Streams
Nested loops

Using Python and Java Swing to create GUIs


len(),count(), and sort()
Working with SQL and JDBC(TM)
Modulus (%)
Python and Java applets
%f format directive
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
Nested dictionaries
and numerous code samples make this book a useful learning experience.
Use of a dictionary with the format operator
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
CONTENTS
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
CONTENTS
Web and Enterprise Applications with Jython
By Richard Hightower

Chapter 5. Organizing
Your Code
Publisher: Addison Wesley
Pub Date: June 28, 2002

Evolution of a Programmer
ISBN: 0-201-61616-5
Table of
Code Blocks andPages:
Namespaces
640
Contents
Modules
Characterized
Functions and
Methods by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
Putting Things Together
novices and professionals alike. In particular, its close relationship to Java(TM) makes
Classes
the two languages, when used in combination, ideal for Web and distributed enterprise
Packages application development.
Globals and the Global Statement
Summary This tutorial begins with coverage of some of the basics of Python programming. Using

plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
Terms in This Chapter
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
Attribute development.
application
Interface

Class Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
Python
Instantiation
and Enterprise Applications with Jython covers important topics such as:
Code block
Introspection
Constructor
Fundamental programming concepts,Keyword
including
statements, expressions,
argument
interpreters, and compilers
Destructor
Main block
Python basics, including operators, string formatting, namespaces, classes, errors,
Encapsulation
and exceptions
Method
First class
object
Object-oriented
programming concepts
Module
Flag File input/output

Namespace

Function
Python's intrinsic functions

Nesting

globalFormatting,
statement, variable,
parsing, and manipulating
strings
Package
namespace
Interfacing with the Java APIs and working
with
Java Streams
Positional
argument
Identity operator
Using Python and Java Swing to create
GUIs
Script
Immutability
Working with SQL and JDBC(TM) Search path
import statement
Python and Java applets
self argument
Instance
In addition, the book contains instructions for downloading and installing the Python
In this chapter, we'lllanguage
cover how
andthewhy
you
should organize
your code.
You'll learn
about namespaces
and code
and
Java
Development
Kit (JDK).
Terminology,
definitions,
explanations,
blocks and about modules,
functions,
classes,
and
methods.
and numerous code samples make this book a useful learning experience.

you are a sophisticated computer user new to programming or a serious


Evolution ofWhether
a Programmer

application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.
As your programs grow, or as you increase your understanding of Python, you'll use more of Python's
organization features. For example:

777

You want to learn how to do a task, so you use the interactive interpreter to learn Python.

Python Programming with the Java Class Libraries: A Tutorial for Building
You want to automate
a task, so you write a script. (See Appendix C on scripts.)
Web and Enterprise Applications with Jython
By Richard Hightower

You want to reuse script functionality, so you organize scripts into different modules.
Addison
Wesley
You want to use Publisher:
generalization
and abstraction
to reuse code common to many scripts, so you organize
scripts into classes.
Pub Date: June 28, 2002

Table
of to share
You want
Contents

ISBN: 0-201-61616-5

modules
with co-workers or a development team, so you organize your modules into
Pages: 640

packages.

Characterized by ease of use, richness of expression, and concise syntax, Python has
You want to use packages of modules from other sources and share your modules with others, so you
remained a premier programming language for more than a decade, and is used by
organize your packages into other packages and into subpackages.
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two you'll
languages,
when
combination,
ideal
for Webeven
and for
distributed
enterprise
Even as your needs change,
still seek
outused
the in
least
sophisticated
approach,
more complicated
application
development.
tasks. For instance, you might write a script to do testing, or you might use interactive mode to learn a new
module or to debug one you've already written.
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
Organizing Your
help Code
those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
No matter how far you
progress and
as a shows
programmer,
you'll
to know
how with
to organize
yourforcode.
In Python, you
capabilities
the ways
thatneed
Python
interfaces
Java APIs
professional
can organize your statements
intodevelopment.
functions and methods; your methods and data into classes; your classes,
application
functions, and statements into modules; your modules into packages; and, lastly, your packages into other
Programming
with the
Java(TM)
Class
Libraries:
A Tutorial
Building
packages.Figure 5-1Python
illustrates
this organization.
The
following
sections
show you
how tofor
achieve
it. Web
and Enterprise Applications with Jython covers important topics such as:
Figure 5-1. Program Organization

Fundamental programming concepts, including statements, expressions,


interpreters, and compilers
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
Object-oriented programming concepts
File input/output
Python's intrinsic functions
Formatting, parsing, and manipulating strings
Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs
Working with SQL and JDBC(TM)
Python and Java applets
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

Nesting

Addison
Classes can havePublisher:
other classes
nestedWesley
within them. Functions and methods can have nested classes
Date: June
28, 2002
as well as nestedPub
functions.
Typically,
the inner classes and functions in a method are small and
serve a purpose onlyISBN:
in the 0-201-61616-5
context of the class in which they nest.

Table of
Contents

Pages: 640

For example, in the following class definition, the class topclass has a member method,
method() ,Characterized
which has an by
inner
function,
function()
, whichand
hasconcise
an innersyntax,
class, Python has
ease
of use, richness
of expression,
innerclass1
. Notice
that topclass
haslanguage
a secondfor
inner
class,
.
remained
a premier
programming
more
thaninnerclass2
a decade, and is used
by

novices and professionals alike. In particular, its close relationship to Java(TM) makes

>>> class
topclass:
the two languages, when used in combination, ideal for Web and distributed enterprise
...
def
method():
application development.
...
def function():
...
class ofinnerclass1:
This tutorial begins with coverage
some of the basics of Python programming. Using
...
pass programming sessions, this book will
plenty of skill-building exercises and interactive
...
class
help thoseinnerclass2:
new to programming develop an understanding of concepts and practical
...
pass
techniques. For
experienced programmers, the book demonstrates Python's breadth of
...
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.

Code BlocksPython
andProgramming
Namespaces
with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
Code blocks are pieces of executable Python code that you can think of as collections of statements. Modules,
classes, and functions are all examples.
Fundamental programming concepts, including statements, expressions,
interpreters,
andonce.
compilers
Modules may be scripts that
execute only
Since Python is unlike other languages in its lack of a main
method, it starts executing code (program text) from the top of the module. To re-execute the module, you have
Python basics, including operators, string formatting, namespaces, classes, errors,
to reload it.
and exceptions
Modules can contain classes and functions (both code blocks), which may be executed many times. Also,
Object-oriented programming concepts
functions can contain classes as well as other functions, and classes can contain methods as well as other classes.
Variables defined in a codeFile
block
are associated with that code block's namespace.
input/output

Python's intrinsic functions

TheandMain
Block
Formatting, parsing,
manipulating
strings
with the
APIs
andsomething
working with
Javathe
Streams
Python may not haveInterfacing
a main method,
butJava
it does
have
similar,
main block, which
looks like this:
Using Python and Java Swing to create GUIs

if __name__ == "__main__"
Working
withhere
SQL and JDBC(TM)
#Put main
code
Python andattribute,
Java applets
Modules have a __name__
which contains the module name (e.g., sys, string,
mymodule). The main block is called __main__ and is executed from the command line. Since
In addition, the book contains instructions for downloading and installing the Python
a module is a code block, anything in it will be executed when it is run from the command line or
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
imported from another module. __name__ thus limits execution to the main module.
and numerous code samples make this book a useful learning experience.
A namespace is a way
to organize
variables
in a largecomputer
program.user
It provides
contexts
individual
Whether
you are
a sophisticated
new to separate
programming
or afor
serious
variables so that twoapplication
with the same
name can
be used
without onewith
adversely
affectingClass
the other.
Think
of
developer,
Python
Programming
the Java(TM)
Libraries
will
namespaces as directories
on insight
your hard
If there
two directories,
user1toand
, and both have a
give you
intodrive.
the power
ofare
Python
and the know-how
putuser2
it to work.
file named readme.txt, you can be sure that these are two different filesone you access as
\user1\readme and the other as \user2\readme.

777

Packages provide namespaces for modules and other packages. Say you create a module called sys but sys is also

the name of a standard


module.
This can cause
problems.
However,
you put your
sys module
in a package
Python
Programming
with
the Java
Class if
Libraries:
A Tutorial
for Building
calledmycompany, you
canand
access
it via mycompany.sys
interfering with the standard sys module.
Web
Enterprise
Applications without
with Jython
Packages also provide
for other packages, just as file directories provide namespaces for each other.
By namespaces
Richard Hightower
Modules provide namespaces
for variables, classes, and functions. You might have a class called stats and
Publisher: Addison Wesley
download a class from the Web also called stats. You can use both classes in the same program because
Pub Date: June 28, 2002
they're in their own modulesmy_module.stats and their_module.stats.
Table of
Similarly,
classes
Contents

ISBN: 0-201-61616-5

Pages: 640 for


namespaces

provide
variables and methods. For example, a method called getMean()
in a class called stat won't interfere with a function called getMean() in the same module.
Characterized by ease of use, richness of expression, and concise syntax, Python has
remained
premierscope
programming
language
more
than
a decade,
and
is used
We'll discuss namespaces
and avariable
more later.
The keyfor
point
here
is that
Python
allows
youbya lot of
novices
and
professionals
alike.
In
particular,
its
close
relationship
to
Java(TM)
makesyour
flexibility in program organization. It also gives you more control over how you manipulate and introspect
the
two
languages,
when
used
in
combination,
ideal
for
Web
and
distributed
enterprise
namespace.
application development.

Modules

This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
helpwe've
thosebeen
new using
to programming
develop
an understanding
of concepts
and Python
practical
Without defining them,
modules since
Chapter
1. These are files
that contain
techniques.
For
experienced
programmers,
the
book
demonstrates
Python's
of
statements and definitions (classes and functions) and can be imported into other modules or intobreadth
the main
capabilities
and
shows
the
ways
that
Python
interfaces
with
Java
APIs
for
professional
module. Module files are identified by the suffix .py.
application development.
If you're a programmer coming from a Java background, you may think that a module is similar to a package.
theyou
Java(TM)
Class
Libraries:
for Building
Web and
Once you work withPython
PythonProgramming
modules for a with
while,
may think
of them
more A
asTutorial
a cross between
a package
and
Enterprise
Applications
with
Jython
covers
important
topics
such
as:
a final public class (with all static variables and a private constructor).

Import

Fundamental programming concepts, including statements, expressions,


interpreters, and compilers
Theimport statement allows you to import classes, functions, and variables from one module into the current
basics, including
formatting,
classes,we'll
errors,
module's namespace. TablePython
5-1 describes
its forms. operators,
Here is an string
example
module, namespaces,
module1.py, which
use
throughout this section to illustrate
import.
and exceptions

def class1:
Object-oriented programming concepts
def method1(self):
File input/output
Table 5-1. Import Statement Forms
Python's intrinsic functions
Form

Description
Formatting, parsing, and manipulating
strings
Imports the module into the current module.
Interfacing with the Java APIs andItems
working
Java Streams
canwith
be accessed
as
Example:import module1
module1.class1,
Using Python and Java Swing to create
GUIs
module1.function1
,
module2.function2. Imports a definition
Working with SQL and JDBC(TM)
from the current module but not the module
itself.
Python and Java applets
from module_name import class_name, Items can be accessed without the module
name
as class1
,function1
but
func_name
In addition, the book contains instructions
for e
downloading
and
installing the;Python
needsexplanations,
the module
language and the Java Development Kitmodule1.function2
(JDK). Terminology, definitions,
Example:from module1
import
class1,
name
to be accessed.
and numerous
code samples
make this book
a useful
learning experience.

import module_name

function1
Whetherimport
you are a sophisticated
computer
user new
to the
programming
serious
from module_name
*
Imports
all of
definitionsorina the
module but
application developer, Python Programming
with
the Java(TM)
Class
Libraries
not the
module
itself. All
items
can bewill
give you insight
into the
and the know-how
to put
it to work.
Example:from module1
import
* power of Python
accessed
without the
module
name as
class1,function1,function2.

def method2(self, arg1, rg2):


self.attribute1 = arg1
self.attribute2 = arg2

777

Python Programming with the Java Class Libraries: A Tutorial for Building

def function1():
Web and Enterprise Applications with Jython
pass
By Richard Hightower
def function2():
Publisher: Addison Wesley
pass
Pub Date: June 28, 2002
def class1:
ISBN: 0-201-61616-5
def
method1(self):
Table
of

Pages: 640
Contents
pass

Characterized by ease of use, richness of expression, and concise syntax, Python has

def method2(self, arg1, arg2):


remained a premier programming language for more than a decade, and is used by
self.attribute1 = arg1
novices and professionals alike. In particular, its close relationship to Java(TM) makes
self.attribute2 = arg2

the two languages, when used in combination, ideal for Web and distributed enterprise
application development.

def function1():
pass
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will

def function2():
help those new to programming develop an understanding of concepts and practical
pass
techniques. For experienced programmers, the book demonstrates Python's breadth of

capabilities and shows the ways that Python interfaces with Java APIs for professional
Breaking things down, we first go to the directory that holds module1.py. Then we start up a new Jython session
application development.
at the command line.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web

C:\Pythonbook\samples\chap5>jython
and Enterprise Applications with Jython covers important topics such as:
Jython 1.0.3 on java1.2fcs
Copyright 1997-1998 Corporation for National Research Initiatives
Fundamental programming concepts, including statements, expressions,
On our first attempt, we use
function1()
, but that results in a NameError, which means that Python
interpreters,
and compilers
didn't find that function in the current namespace.
Python basics, including operators, string formatting, namespaces, classes, errors,
Next we try function1()
with the module name, but again that produces a name error because module1 is
and exceptions
not in the current namespace.
Object-oriented programming concepts

>>> module1.function1()
Traceback (innermost
last):
File input/output
File "<stdin>", line 1, in ?
NameError: module1
Python's intrinsic functions

So we import module1 intoFormatting,


the current parsing,
namespace
use function1()
as follows:
andand
manipulating
strings

>>> import module1


Interfacing with the Java APIs and working with Java Streams
>>> module1.function1()
Using Python and Java Swing to create GUIs
After we import module1, we can call function1() using the module1.function1() form.
Working with SQL and JDBC(TM)

>>> function1
Python and
Java applets
Traceback (innermost
last):
File "<stdin>", line 1, in ?
In addition, the book contains instructions for downloading and installing the Python
NameError: function1

language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous
code
make
this book a useful
learning
experience.
Yet again, a name error.
The problem
is samples
that to use
function1()
without
the module
name we have to
importfunction1() from module1.
Whether you are a sophisticated computer user new to programming or a serious
application
developer,
Python Programming with the Java(TM) Class Libraries will
>>> from module1
import
function1
>>> function1give you insight into the power of Python and the know-how to put it to work.

<function function1 at -1811886282>

777

Finally, we use the from module import* form with module1 and then dir() to see the contents of the
current namespace. Notice that all of the items in the module have been imported, even the variables string1

andnumber1.

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
module1
import
*
By Richard
Hightower

>>> from
>>> dir ()
['__name__', 'class1',
'function1', 'function2', 'module1', 'number1', 'strin
Publisher: Addison Wesley
Pub Date: June 28, 2002

Table of
Contents

ISBN: 0-201-61616-5
Pages: 640

Immutability

Althoughstring1
and number1
the current
namespace,and
they're
not the
samePython
as the has
Characterized
by ease ofare
use,inrichness
of expression,
concise
syntax,
variables in module1.
first, theyprogramming
refer to the same
object.
remainedAta premier
language
for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
>>> import
module1
the two languages, when used in combination, ideal for Web and distributed enterprise
>>> module1.number1
is number1
application development.

This tutorial begins with coverage of some of the basics of Python programming. Using

returns 1
which
means true
plenty
of skill-building
exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
However, theytechniques.
no longer both
refer to that programmers,
object once their
change. That's
becausebreadth
they areof
For experienced
the values
book demonstrates
Python's
immutable. Here's an example of number1:
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
>>> module1.number1
= 600

>>> module1.number1
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
600
and Enterprise Applications with Jython covers important topics such as:
>>> number1
1
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers

>>> module1.number1 is number1


Python basics, including operators, string formatting, namespaces, classes, errors,
0
and exceptions

>>> #returns 0 which means false


Object-oriented programming concepts
Here's the same example using string1:
File input/output

>>> module1.string1 is string1


Python's intrinsic functions
1
Formatting, parsing, and manipulating strings

>>> string1 = "hi"


>>> module1.string1
is the
string1
Interfacing with
Java APIs and working with Java Streams
0
Using Python and Java Swing to create GUIs

>>> module1.string1 == string1


0
Working with SQL and JDBC(TM)
Python and Java applets
>>> module1.string1
'Hello, how are you?'

In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
Module Search Path
and numerous code samples make this book a useful learning experience.
Whether modules
you are afrom
sophisticated
newthe
to programming
a serious
So far, we've been importing
one placecomputer
to anotheruser
within
same directoryorthey
were written in.
application
Python
Programming
with the
Java(TM)
Libraries
However, as you write
more anddeveloper,
more modules,
you'll
want to organize
them
across Class
directories.
You will
can do this
give
into the
power
of Python
and the know-how
put it to
work.
as long as the modules
areyou
in insight
your module
search
paththe
equivalent
of the DOStoPATH
environmentwhich
tells Python where to look for Python modules.

777

For CPython, you set the module search path by declaring the PYTHONPATH environment variable. You can't
do this in Jython because you can't access environment variables in Java. Instead, you access the search path in

the registry file, which


is similar
to *.ini fileswith
in Windows
or toClass
the Windows
registry.
Python
Programming
the Java
Libraries:
A Tutorial for Building
Web and Enterprise Applications with Jython

You can edit the registry


(C:\Jython\Registry)
with your favorite text editor. The module search path is stored in
By Richard
Hightower
a registry setting called python.path.
Publisher: Addison Wesley

#Python Registry

Pub Date: June 28, 2002

python.path=.;
Table of
... Contents
...

ISBN: 0-201-61616-5
Pages: 640

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained
a premier
for moreonly.
thanIfawe
decade,
is used
by search
In the example above,
the registry
settingprogramming
points to the language
current directory
want and
Jython
to always
novices
and
professionals
alike.
In
particular,
its
close
relationship
to
Java(TM)
makes
a directory called C:\Python\modules, we set python.path as follows (note the semicolons to delimit
the
two
languages,
when
used
in
combination,
ideal
for
Web
and
distributed
enterprise
directories, as for the DOS PATH environment variable):
application development.

python.path=.;c:\\python\\modules;
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those
new toisprogramming
understanding
of concepts and practical
This means that the current
directory
searched first,develop
then theanC:\JythonLib
directory.
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.

sys

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and
Enterprise
Applications
withmodule
Jythonsearch
coverspath
important
as:
Thesys module
holds
the current
value of the
in the topics
pathsuch
variable.

>>> sys.path
Fundamental programming concepts, including statements, expressions,
['.', 'C:\\Jython\\Lib']
interpreters, and compilers

Let's edit the python.path module


include
C:\Python\modules.
Open
the registry
file in yourclasses,
favoriteerrors,
editor,
Python to
basics,
including
operators, string
formatting,
namespaces,
and set python.path to .;C:\\Python\\modules.
Then start up an interactive session, and query the value of
and exceptions
python.path.
Object-oriented programming concepts

>>> import sys


>>> sys.path
File input/output
['.', 'C:\\Python\\modules', 'C:\\Jython-1.0\\Lib']
Python's intrinsic functions
To test if this is working, create the directory C:\Python\modules, and create a module called path.py.
Formatting, parsing, and manipulating strings

def youfoundme():
Interfacing
print "You found
me" with the Java APIs and working with Java Streams
Using Python
andanywhere
Java Swing
GUIs Start up the Jython interpreter, and try
Putpath.py in C:\Python\modules.
Now go
elsetoincreate
the directory.
to import path.py.
Working with SQL and JDBC(TM)

C:\>jython
Python and Java applets
Jython 1.0.3 on java1.2fcs
Copyright 1997-1998 Corporation for National Research Initiatives
In addition, the book contains instructions for downloading and installing the Python
>>> import path
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
>>> path.youFoundMe()
and numerous code samples make this book a useful learning experience.
You found me
Whether you are a sophisticated computer user new to programming or a serious
Becausesys.path is a list, you can add paths at runtime.
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

Warning

Addison
Wesley it loads the first one it finds on python.path. That means
When Python is Publisher:
trying to import
a module,
Date:called
June 28,
that, if you have aPub
module
path2002
in your current directory that has the following listing:

Table
of
path.py
Contents

ISBN: 0-201-61616-5

listing
Pages:of
640path in current path:
print "Wrong one dummy"
Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
and you try tonovices
import it
from
that directory,
you
get the its
wrong
This can to
beJava(TM)
a difficultmakes
and
professionals
alike.
Inwill
particular,
closeone.
relationship
problem to debug,
especially
if
the
first
module
in
the
path
is
an
older
version
of
the
one you're
the two languages, when used in combination, ideal for Web and distributed
enterprise
trying to load.application development.

>>> import
path
This tutorial begins with coverage of some of the basics of Python programming. Using
Wrong one
dummy
plenty of skill-building exercises and interactive programming sessions, this book will

Functions

help those new to programming develop an understanding of concepts and practical


techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
and
Methods
application development.

Remember that a function


a code block and
blocks
are collections
of Tutorial
statements.
are similar
PythonisProgramming
withthat
the code
Java(TM)
Class
Libraries: A
for Methods
Building Web
to functions, and youand
define
them the
same way. The
difference
is that, unlike
functions,
Enterprise
Applications
with only
Jython
covers important
topics
such as: methods are
associated with classes and are defined within them. Because of the similarities, the terms function and method
will be used interchangeably in this section.
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers

Step by Step: Defining and Calling a Method

Python basics, including operators, string formatting, namespaces, classes, errors,


To define, or declare, a function
or method, you enter the keyword def followed by the function name, a list of
and exceptions
arguments enclosed in parentheses, and finally a colon. Next come the statements, which make up the body of
programming
concepts
the function. They start on Object-oriented
a new line and, like
all code blocks,
are indented (if you don't indent, you'll get an
error). The statements are where the action is.
File input/output
Here's an example of a simple function, sayHello():
Python's intrinsic functions

>>> def sayHello (strName):


parsing,
manipulating strings
...
strHello Formatting,
= "Hello
" +and
strName
...
print (strHello)
Interfacing with the Java APIs and working with Java Streams
...
Using Python and Java Swing to create GUIs

>>> sayHello("Mom")
Hello Mom
Working with SQL and JDBC(TM)
>>> sayHello("Dad")
Python and Java applets
Hello Dad

In addition, the book contains instructions for downloading and installing the Python
Here's the breakdown.
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
First we define a method called sayHello() with the argument strName.
Whether you are a sophisticated computer user new to programming or a serious
>>> def sayHello
(strName):
application
developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.
Then we add two statements. The first takes the string literal "Hello" and the function argument strName
and concatenates them. It then assigns their value to the strHello variable.

...

777

strHello = "Hello " + strName

The second statementPython


prints out
the value of with
strHello
to the
console.
Programming
the Java
Class
Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython

...

printByRichard
(strHello)
Hightower

Next we invoke this function a couple of times, each time substituting a value for strHello . Notice that we
Publisher: Addison Wesley
invoke this function the same way we invoke the built-in functions.
Pub Date: June 28, 2002

ISBN: 0-201-61616-5
>>> Table
sayHello("Mom")
of

Pages:
640
Hello
Mom
Contents

Characterized by ease of use, richness of expression, and concise syntax, Python has
>>> sayHello("Dad")
remained a premier programming language for more than a decade, and is used by
Hello Dad
novices and professionals alike. In particular, its close relationship to Java(TM) makes
ThesayHello()the
function
doesn't return
fact, all functions
return
None
by default.enterprise
two languages,
whena value.
used inIncombination,
ideal for
Web
and distributed
application development.
Now we'll create a function, sumNumbers(), that does return a value; it sums two numbers and returns the
This tutorial begins with coverage of some of the basics of Python programming. Using
total.
plenty of skill-building exercises and interactive programming sessions, this book will
>>> def sumNumbers(x,
y):
help those new to
programming develop an understanding of concepts and practical
...
return
x + yFor experienced programmers, the book demonstrates Python's breadth of
techniques.
...
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.

>>> sumNumbers(5, 10)


15
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
Of course, most functions are more useful, and more complex, than these examples. They can have any number
of arguments and can be stored for later use by more than one program.
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers

Calling Methods and Defining Arguments

Python basics, including operators, string formatting, namespaces, classes, errors,


There are three ways to calland
a method:
by positional arguments, by keyword arguments, and by a combination of
exceptions
the two. There are three ways to define a method: with default values, with a variable number of positional
arguments, and with a variable
number of keyword
arguments.
Object-oriented
programming
concepts
Consider the following method:
File input/output

>>> def sayHello(name,


title,
message):
Python's intrinsic
functions
...
print ("Hello " + title + " " + name + " " + message)
Formatting, parsing, and manipulating strings
...
Interfacing
with the Java APIs and working with Java Streams
It can be called using positional
arguments:
Using Python and
Java Swing
to create
>>> sayHello("Hightower",
"Mr.",
"How
areGUIs
you")
Hello Mr. Hightower How are you
Working with SQL and JDBC(TM)
or using keyword arguments (keyword=value):
Python and Java applets

>>> sayHello(name="Hightower", title="Mr.", message="How are you")


In addition, the
book
contains
Hello Mr. Hightower
How
are
youinstructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
numerous
code
samples
make
a useful
learning
Keywords equate to and
argument
names.
You
can use
themthis
in book
any order,
which
meansexperience.
that in the last example we
could have put the message keyword in the first position.
Whether you are a sophisticated computer user new to programming or a serious
application developer, are
Pythonyou?",
Programming
with the Java(TM) Class title="Mr.")
Libraries will
>>> sayHello(message="How
name="Hightower",
give you insight
the power
Hello Mr. Hightower
Howintoare
you?of Python and the know-how to put it to work.
In the combined form, you can use one positional argument and two keywords.

777

>>> sayHello("Hightower", message="How are you?", title="Mr.")

Hello Mr. Hightower


How are with
you?
Python Programming
the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython

Calling methods withBykeywords


doesn't seem very useful; so far it just adds more typing. The payoff comes when
Richard Hightower
you use keywords with default arguments.
Publisher: Addison Wesley

Continuing the previous example, if we want default values for title and name, we first define our function
Pub Date: June 28, 2002
with two default arguments.

>>>
...
...

ISBN: 0-201-61616-5
Table of
Pages:
640title="Mr.",
def sayHello(name,
Contents

message="Hello %s %s, how are you?"):


print message % (title, name)

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
professionals
alike. Inargument.
particular, its close relationship to Java(TM) makes
Now we can use thenovices
functionand
with
only one positional
the two languages, when used in combination, ideal for Web and distributed enterprise
>>> sayHello("James
Estrada")
application development.

Hello Mr. James Estrada, how are you?


This tutorial begins with coverage of some of the basics of Python programming. Using
If we need to, we canplenty
override
the default values.
of skill-building
exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
>>> sayHello("Mark
"Dr.")
techniques.Green",
For experienced
programmers, the book demonstrates Python's breadth of
Hello Dr. Mark
Green,
how
are
you?
capabilities and shows the ways
that Python interfaces with Java APIs for professional
application development.

>>> sayHello("Ally McBeal", "Ms.")


Hello Ms. Ally
McBeal,
howwith
are
Python
Programming
the you?
Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
Notice that both of these functions use positional arguments.

Another way to override default


arguments
is with keywords.
Let's
say thatstatements,
we want toexpressions,
override the last argument
Fundamental
programming
concepts,
including
from above.
interpreters, and compilers

>>> sayHello("Al Python


McMeal",
message="Hello
%s, are
you hungry,
would you lik
basics, including
operators, string%s
formatting,
namespaces,
classes, errors,
Hello Mr. Al McMeal,
are you hungry, would you like to go to lunch?
and exceptions
This comes in handy whenObject-oriented
there are ten arguments
with default
arguments and you want to override only the
programming
concepts
tenth one.
File input/output
This example won't work because name has no default value.
Python's intrinsic functions

>>> sayHello(title="Mrs.", message="Hi %s %s, how are you doing? How is your
Traceback (innermost
last):
Formatting,
parsing, and manipulating strings
File "<stdin>", line 1, in ?
Interfacing
with enough
the Java APIs
and working with
Java Streams
TypeError: sayHello()
not
arguments;
expected
Using Python and Java Swing to create GUIs

Putting Things Together

Working with SQL and JDBC(TM)


Recall from Chapter 4 that we wrote a function called getMean() that figured the average of a set of house
Python
and Java
prices. Well, we can change
it to accept
twoapplets
default arguments. The first argument, sample, is a flag that tells
getMean() if theInsetaddition,
of numbers passed to it is from a sample of a population or the population as a whole.
the book contains instructions for downloading and installing the Python
(The mean and the average of a sample are calculated differently.) The second argument, display, is a flag
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
that tells getMean() to optionally display the results to the monitor.
and numerous code samples make this book a useful learning experience.

getMean()

Whether you are a sophisticated computer user new to programming or a serious


application developer, Python Programming with the Java(TM) Class Libraries will
give defined:
you insight into the power of Python and the know-how to put it to work.
Here'sgetMean()()

def getMean (nums, sample=0, display=0):


for x in nums:
sum = sum + x

777

if(sample):Python Programming with the Java Class Libraries: A Tutorial for Building
averageWeb
= and
sumEnterprise
/ (len(nums)-1)
Applications with Jython
else:
By Richard Hightower
average = sum / len(nums)
if(display): Publisher: Addison Wesley
print ("mean
= June
" +28,
'average')
Pub Date:
2002
return average ISBN: 0-201-61616-5

Table of

Contents
Here are
some examples:

Pages: 640

Characterized
use, richness of expression,
#Define example
sampleby ease
andofpopulation
numbersand concise syntax, Python has
remained
a
premier
programming
language
for more than a decade, and is used by
sample =(1,2,3,3,2,1,1,1,2,2,3,3,2,2,2,2,2,2,2,2,2,2,2,2)
novices
and
professionals
alike.
In
particular,
its close relationship to Java(TM) makes
population=(1,2,3,3,2,1,1,1,2,2,3,3,2,2,2,2,2,2,2,2,2,2,2,2)
the
two
languages,
when
used
in
combination,
ideal for Web and distributed enterprise
#call with positional arguments
application
development.
populationMean = getMean(population, 0)
#call using default arguments
This tutorial begins with coverage of some of the basics of Python programming. Using
#call using default arguments
plenty of skill-building exercises and interactive programming sessions, this book will
sampleMean = getMean(sample)
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
print ("population mean " + 'populationMean')
capabilities and shows the ways that Python interfaces with Java APIs for professional
print ("sample mean " + 'sampleMean')
application development.

#call with Python


positional
arguments
and Class
print
Programming
with the Java(TM)
Libraries: A Tutorial for Building Web
populationMean
=
getMean(population,
0,
1)important topics such as:
and Enterprise Applications with Jython covers
#call using keyword arguments
Fundamental programming
concepts, including statements, expressions,
sampleMean = getMean(sample,
display=1)
interpreters, and compilers
The script (in the samples/chap5 directory) essentially demonstrates the use of keywords to include default and
Python basics, including operators, string formatting, namespaces, classes, errors,
keyword arguments.
and exceptions
The following definition says in English, "Define a method called getMean() with three arguments":
Object-oriented programming concepts

def getMean (nums, sample=1, display=0):


File input/output
The first argument, nums, holds the input numbers; the second, sample=1 , tells getMean() whether or
Python's intrinsic
functions
not this is a sample or a population;
and the third,
display=0, tells getMean() whether or not it should
display the mean to the console. Remember that Python doesn't have a Boolean (true/false) type, so any nonzero
manipulating
strings
value (1 above) equals trueFormatting,
and a zero parsing,
value (0and
above)
equals false.
Interfacing with the Java APIs and working with Java Streams
if(sample):
average = sum / (len(nums)-1)
Using Python and Java Swing to create GUIs
else:
average = sum
/ len(nums)
Working with SQL and JDBC(TM)
Once again, in English this says, "If sample is equal to true, do the first equation to figure the mean; else, do
Python and Java applets
the second equation." When this method is invoked without sample specified, the default is true. In that case,
average = sum/(len(nums)-1
is invoked.
If sample
is false, average
= the Python
In addition, the book contains
instructions
for downloading
and installing
sum/len(nums)language
is invoked.
and the Java Development Kit (JDK). Terminology, definitions, explanations,

and numerous code samples make this book a useful learning experience.
Thedisplay argument works like the sample argument.
Whether you are a sophisticated computer user new to programming or a serious

if(display): application developer, Python Programming with the Java(TM) Class Libraries will
print ("mean
= " + 'average')
give you insight into the power of Python and the know-how to put it to work.
That is, "If display is true, print the mean to the console."

777

Variable Number of Arguments

Here we use the asterisk


symbol
(*) to definewith
a variable
number
of nums
arguments:
Python
Programming
the Java
Class
Libraries:
A Tutorial for Building
Web and Enterprise Applications with Jython

>>> def sum(*nums):


By Richard Hightower
...
total = 0
...
for numPublisher:
in nums:
Addison Wesley
...
total
= 28,
total
Pub Date: June
2002 + num
...
return total
ISBN: 0-201-61616-5
... Table of
Pages: 640
Contents

nums is a sequence, so it works with the for statement. The sum() function iterates through each num in the
Characterized by ease of use, richness of expression, and concise syntax, Python has
variable argument list.
remained a premier programming language for more than a decade, and is used by
novices
alike.
particular,but
its see
close
relationship
to Java(TM)
makes
At first it may look as
thoughand
weprofessionals
could have used
anyInsequence,
how
we call sum()
.
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
>>> sum(19,20,21)

60
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty
of skill-building
exercises andis interactive
programming
sessions, this book will
Note that the variable
number
of argument declarations
of type Tuple
.
help those new to programming develop an understanding of concepts and practical
>>> def func(*args):
techniques. For experienced programmers, the book demonstrates Python's breadth of
...
printcapabilities
type(args)
and shows the ways that Python interfaces with Java APIs for professional
...
application development.

>>> func()
Python Programming with the Java(TM)
Class Libraries: A Tutorial for Building Web
<jclass org.python.core.PyTuple
at -801600693>
and Enterprise Applications with Jython covers important topics such as:
You can mix and match multiple arguments with the positional arguments, as in this nostalgic printf()
example:
Fundamental programming concepts, including statements, expressions,
interpreters,*args):
and compilers
>>> def printf(format,

...
...

print format % args

Python basics, including operators, string formatting, namespaces, classes, errors,


and exceptions
Here are some other examples:
Object-oriented programming concepts

>>> printf ("Hi %s, how is %s?", "Martha", "Miguel")


input/output
Hi Martha, how isFileMiguel?
Python's intrinsic functions

>>> printf ("Martha is %i, Miguel is %i", 30, 29)


Martha is 30, Miguel
is parsing,
29
Formatting,
and manipulating strings
Programmers, if you're familiar
with C,with
youthe
canJava
see APIs
that C's
and
Python's
are similar. With the way
Interfacing
andprintf()
working with
Java
Streams
we've defined printf() , you need at least one argument and can have as many as you like.
Using Python and Java Swing to create GUIs
Variable Number of Keyword Arguments (with Dictionary)
Working with SQL and JDBC(TM)
Another way to declare multiple keyword arguments is with the double asterisk symbol ( **).
Python and Java applets

>>> def printKeywords(**keywords):


In addition,
book contains instructions for downloading and installing the Python
...
for item
in the
keywords.items():
language
and
the
Java Development Kit (JDK). Terminology, definitions, explanations,
...
print item
and
numerous
code
samples make this book a useful learning experience.
...
Whether
a sophisticated
computer
user new to programming or a serious
You can use this function
withyou
anyare
number
of keyword
arguments.
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the powereyes="blue",
of Python and the know-how
to put it to work.
>>> printKeywords(name="Whit",
weight="28",
age="2")

('age', '2')
('weight', '28')
('eyes', 'blue')
('name', 'Whit')

777

Python Programming with the Java Class Libraries: A Tutorial for Building
The variable (i.e., changeable)
keyword argument is a dictionary, which we can prove.
Web and Enterprise Applications with Jython
By Richard Hightower
func(**args):

>>> def
...
print type (args)
Publisher: Addison Wesley
...
Pub Date:
June 28,
2002
>>> func (arg=1,
arg2=2,
arg3=3)
ISBN: 0-201-61616-5
<jclass org.python.core.PyDictionary
at -1146189863>

Table of
Contents

Pages: 640

Variable keyword arguments (**) can be mixed and matched with variable positional arguments (*) and regular
arguments to improve
the workingsbyofease
a function.
Here's anofexample
usingand
printf()
:
Characterized
of use, richness
expression,
concise syntax,
Python has
remained a premier programming language for more than a decade, and is used by
>>> def printf(format,
*args,alike.
**kargs):
novices and professionals
In particular, its close relationship to Java(TM) makes
...
if(len(args)):
the two languages, when used in combination, ideal for Web and distributed enterprise
...
print
(format % args)
application
development.

...
...
...
...
...

elif(len(kargs)):
printbegins
(format
% kargs)
This tutorial
with coverage
of some of the basics of Python programming. Using
else:plenty of skill-building exercises and interactive programming sessions, this book will
print
format
help those
new to
programming develop an understanding of concepts and practical

techniques. For experienced programmers, the book demonstrates Python's breadth of


capabilities and shows the ways that Python interfaces with Java APIs for professional
Nowprintf() can
accept any
number of keyword or positional arguments.
application
development.

>>> printf("Hi
%s",
"Missy")
Python
Programming
with the Java(TM) Class Libraries: A Tutorial for Building Web
Hi Missy
and Enterprise Applications with Jython covers important topics such as:
>>> printf("Hi %(name)s", name="Missy")
Fundamental programming concepts, including statements, expressions,
Hi Missy
interpreters, and compilers

>>> printf("Hi Missy")


Python basics, including operators, string formatting, namespaces, classes, errors,
Hi Missy
and exceptions
Step by Step

Object-oriented programming concepts

Define a function, printf()


, with one positional argument, format; one variable argument, args; and
File input/output
one variable keyword argument, kargs.
Python's intrinsic functions

>>> def printf(format *args, **kargs):


Formatting, parsing, and manipulating strings
Check if the args tuple has items in it.
Interfacing with the Java APIs and working with Java Streams

...

if(len(args)):

Using Python and Java Swing to create GUIs


If so, use it in the format % args expression as the tuple in a string format operation. Print the expression.
Working with SQL and JDBC(TM)

...

print (format % args)

Python and Java applets


Ifargs is empty, check if the kargs dictionary has items in it. Print the resulting format % kargs
expression.
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
...
elif(len(kargs)):
and numerous code samples make this book a useful learning experience.

...

print (format % kargs)

Whether you are a sophisticated computer user new to programming or a serious


If both args and kargs
are empty,
printPython
the format
string by itself.
application
developer,
Programming
with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

...
...
...

else:

print format

777

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

if(args)

Publisher:
Addison
Wesley
In the printf()
example,
we used
the statement if(len(args)): to determine whether
Pubof
Date:
June 28,
2002
the variable number
positional
arguments
was equal to zero. Instead, we could have used
if(args) to see if the list
has 0-201-61616-5
items in it, rewriting printf() as
ISBN:

Table of
Contents

Pages: 640

def printf(format, *args, **kargs):


if(args):
Characterized by ease of use, richness of expression, and concise syntax, Python has
print
(format
args) language for more than a decade, and is used by
remained
a premier %programming
elif(kargs):
novices
and professionals alike. In particular, its close relationship to Java(TM) makes
print
% kargs)
the two(format
languages, when
used in combination, ideal for Web and distributed enterprise
else: application development.
print format
This tutorial begins with coverage of some of the basics of Python programming. Using
Remember that
an empty
dictionary isexercises
equivalent
false in a Boolean
test. sessions, this book will
plenty
of skill-building
andtointeractive
programming
help those new to programming develop an understanding of concepts and practical
Of course, you can also rewrite printf() to be very readable.
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows
the ways
that Python interfaces with Java APIs for professional
def printf(format,
*args,
**kargs):
application >development.
if(len(args)
0):

print
(format % args)
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
elif(len(kargs)
> 0):
and Enterprise Applications with Jython covers important topics such as:
print (format % kargs)
else:
print Fundamental
format programming concepts, including statements, expressions,
interpreters, and compilers
This approach makes the code a little verbose, but readability should win out. In six months when
you need to read thePython
code you
wrote
(to figure
out whatstring
it's doing
so you can
change it),classes,
you'll be
basics,
including
operators,
formatting,
namespaces,
errors,
happy.
and exceptions
Object-oriented
programming
Remember, functions are code
blocks and code
blocks areconcepts
collections of statements. Default function argument
values save time.
File input/output

Classes

Python's intrinsic functions

Formatting, parsing, and manipulating strings


A class consists of data and the functions that act on that data. In classes, functions are referred to as methods. A
way to understand classes is
to think ofwith
them
functions
withworking
multiplewith
entryJava
points.
In this way they provide
Interfacing
theasJava
APIs and
Streams
data encapsulation.
Using Python and Java Swing to create GUIs
You define a class with the class keyword.
Working with SQL and JDBC(TM)

class class_name:
class_attributes
Python and Java applets
Classes can have many
attributes.the
These
be variables
or definitionsand
of either
functions
or other
In addition,
bookattributes
contains can
instructions
for downloading
installing
the Python
classes. For example,language
the definition
ofJava
the class
chapter
threeTerminology,
variable attributes:
and the
Development
Kithas
(JDK).
definitions, explanations,
number_of_pages
,title, and
.
and numerous
codetoc
samples
make this book a useful learning experience.

class chapter:
Whether you are a sophisticated computer user new to programming or a serious
number_of_pages
= 20
application developer,
Python Programming with the Java(TM) Class Libraries will
titlegive
= you
"Organizing
yourof program"
insight into the power
Python and the know-how to put it to work.
toc = ["Introduction", "Modules", "Functions", "Packages", "Classes"]

777

Notice that the class attributes are indented, just as the subordinate statements in an if statement are indented.

Class attributes can be


accessed
with the form
class_name.attribute
Python
Programming
with
the Java Class Libraries: .A Tutorial for Building
Web and Enterprise Applications with Jython

chapter.number_of_pages
= 30
By Richard Hightower
print `chapter.number_of_pages`
toc.append("Scope
and Namespaces")
Publisher: Addison Wesley
Pub Date: June 28, 2002

Classes can also have function definitions (book.py).


Table of

class
chapter:
Contents

ISBN: 0-201-61616-5

Pages: 640

""" Document String for chapter class """


Characterized
number_of_pages
= 20by ease of use, richness of expression, and concise syntax, Python has
remained
a premier
programming
language for more than a decade, and is used by
title = "Organizing
your
program"
novices
and
professionals
alike.
In
particular,
its close relationship to Java(TM) makes
toc = ["Introduction", "Modules",
\
the
two
languages,
when
used
in
combination,
ideal for Web and distributed enterprise
"Functions", "Packages", \
application
development.
"Classes"]
def print_me(self):
This tutorial begins with
of some of the basics of Python programming. Using
print chapter.title
+ coverage
" " +`chapter.number_of_pages`
plenty
of
skill-building
exercises
and
for section in chapter.toc: interactive programming sessions, this book will
help those
programming develop an understanding of concepts and practical
print
" "new
+ to
section

techniques. For experienced programmers, the book demonstrates Python's breadth of


capabilities
and shows
the waystothat
Python
interfaces
with Java
APIs
forand
professional
Note here that the function
definitions
are indented
show
that they're
members
of the
class
that their
application
development.
subordinate statements
are further
indented to show that they belong to the functions. The point to remember is
thatindentation shows ownership or mem bership.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

For Programmers: self

Fundamental programming concepts, including statements, expressions,


interpreters, and compilers
Theself argument to the print-me() method in the chapter class holds the reference to
the class instance. It's
similar
to theincluding
this reference
in string
Java orformatting,
the Me reference
in Visual
Basic.
Python
basics,
operators,
namespaces,
classes,
errors,
and exceptions

Exploring a Defined
Class programming concepts
Object-oriented
Fileininput/output
For this section, follow along
the interactive session by loading class chapter using the -i option in
Jython. You'll find chapter in module book.py in directory chap5. Here's the prompt:
Python's intrinsic functions

C:\python\book\chap5>jython -i book.py
Formatting, parsing, and manipulating strings
Now enter

Interfacing with the Java APIs and working with Java Streams

>>> dir()
Using Python and Java Swing to create GUIs
['__name__', 'chapter']
Working
SQL and
JDBC(TM)
Thedir() built-in function
with nowith
arguments
gives
you the names in the current namespace. If we supply it
with the argument chapter, it gives us chapter's attributes.
Python and Java applets

>>> dir(chapter)
In addition, the book contains instructions for downloading and installing the Python
['__doc__', '__module__', 'number_of_pages', 'print_me', 'title', 'toc']
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous
code samples
make
this the
book
a useful learning
experience.
The__doc__ attribute
holds the class's
document
string;
__module__
attribute
holds its associated
module. The rest of the attributes are ones we defined for chapter. Note that print_me() is listed as an
Whether you are a sophisticated computer user new to programming or a serious
attribute.
application developer, Python Programming with the Java(TM) Class Libraries will
youwith
insight
into the
power of Python and the know-how to
We call a method ofgive
a class
the form
class_name.method_name()
. put it to work.

>>> chapter.print_me(None)
Organizing your program 20
Introduction

777

Modules Python Programming with the Java Class Libraries: A Tutorial for Building
FunctionsWeb and Enterprise Applications with Jython
Packages ByRichard Hightower
Classes
Publisher: Addison Wesley

This is similar to callingPub


a regular
function, the only difference being that the function name must be prepended
Date: June 28, 2002
with the class name. The syntax looks a lot like the syntax for calling a function in a module.
Table of
we had
imported
Contents

ISBN: 0-201-61616-5

Pages: 640

If
the book.py module (instead of loading it at the command line with Jython), we would have
had to use the module name to call print_me().
Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
module_name.class_name.function_name.
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
>>> import book
application development.
>>> book.chapter.print_me(None)

Organizing your program 20


This tutorial begins with coverage of some of the basics of Python programming. Using
Introduction
Modules plenty of skill-building exercises and interactive programming sessions, this book will
Functionshelp those new to programming develop an understanding of concepts and practical
Packages techniques. For experienced programmers, the book demonstrates Python's breadth of
Classes capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
First Class Object
and Enterprise Applications with Jython covers important topics such as:
In the print_me() example, we passed the argument None. The first argument in a method
Fundamental
programming
concepts,
including
statements,
usually refers to an instance
of a class,
but not here.
Instead
we're using
the classexpressions,
itself because, in
and compilers
Python, the class is ainterpreters,
first class object.

Python basics, including operators, string formatting, namespaces, classes, errors,


To access the member variables in chapter we use the form class_name.variable_name. Again,
and exceptions
the syntax is like that for accessing variables in a module.
Object-oriented programming concepts

>>> chapter.number_of_pages, chapter.title


(20, 'Organizing File
your
program')
input/output
>>> chapter.toc
['Introduction', Python's
'Modules',
'Functions', 'Packages', 'Classes']
intrinsic functions
Here we accessed both number_of_pages
andmanipulating
title (the tuple
format). Python returned a tuple containing
Formatting, parsing, and
strings
the values of number_of_pages and title, respectively. Then we accessed the values in the member list
Interfacing with the Java APIs and working with Java Streams
calledtoc.

Using Python
and Java Swing to create GUIs
We can also change the attributes
of a class.
Working with SQL andand
JDBC(TM)
>>> chapter.toc.append("Scope
Namespaces")
Python and Java applets
>>> chapter.title="Organizing
your code"
In addition, the book contains
instructions for downloading and installing the Python
>>> chapter.number_of_pages
= 30

language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous
samples make
this book a useful learning experience.
To confirm the changes,
we run thecode
print_me()
function.
Whether you are a sophisticated computer user new to programming or a serious
>>> chapter.print_me(None)
application
developer,
Programming
with the
Java(TM) Class
Librariesand
will functions 30
Organizing your
Python
codePython
into
packages,
modules,
classes
give
you
insight
into
the
power
of
Python
and
the
know-how
to
put
it
to
work.
Introduction
Modules
Functions
Packages
Classes

777

Scope andPython
Namespaces
Programming with the Java Class Libraries: A Tutorial for Building

Class

Web and Enterprise Applications with Jython


By Richard Hightower
Instances

Publisher:
Addison
Wesley
Say we want to create 20
chapter
classes.
To do this with what we've learned so far, we'd have to redefine
chapter 20 times. Pub Date: June 28, 2002
ISBN: 0-201-61616-5

Table of
class
chapter1: Pages: 640

Contents
number_of_pages = 1
...
Characterized by ease of use, richness of expression, and concise syntax, Python has

remained a premier programming language for more than a decade, and is used by

class chapter2:
novices and professionals alike. In particular, its close relationship to Java(TM) makes
number_of_pages
= 2
the two languages,
when used in combination, ideal for Web and distributed enterprise
...
application development.
This tutorial begins with coverage of some of the basics of Python programming. Using
class chapter3:
plenty of =
skill-building
exercises and interactive programming sessions, this book will
number_of_pages
3
help
those
new
to
programming
develop an understanding of concepts and practical
...
techniques. For experienced programmers, the book demonstrates Python's breadth of
Time consuming, isn't
it? With what
we're about
to learn,
we caninterfaces
instead create
instance
of chapter
capabilities
and shows
the ways
that Python
with an
Java
APIs for
professionalfor
each chapter in our book.
application development.
Think of a class as aPython
cookie Programming
cutter and an instance
an actualClass
cookie.
You useAthe
cookiefor
cutter
to stamp
with the as
Java(TM)
Libraries:
Tutorial
Building
Webthe
cookie out. With classes,
stamping out
the class instances
is called
and Enterprise
Applications
with Jython
coversinstantiation.
important topics such as:
When a class is instantiated, the instance shares all of its attributes. The attributes of both initially refer to the
Fundamental
programming
concepts,(just
including
expressions,
same objects, but the instance
can also define
its own attributes
as youstatements,
can decorate
each cookie a different
interpreters,
compilers
way). You access the instance
attributesand
with
the form instance_name.attribute . This form refers to
the class attributes if the instance hasn't defined its own, or to its own if it has.
Python basics, including operators, string formatting, namespaces, classes, errors,
and than
exceptions
This concept is easier to show
to explain, so we'll instantiate our chapter class to illustrate. For the next
interactive session, load module book.py using the jython-i option.
Object-oriented programming concepts
First we assign chap1 to the results of the class constructor expression, which is an instance of class
File input/output
chapter.

Python's intrinsic functions


>>> chap1 = chapter()
Formatting, parsing, and manipulating strings

For
Programmers:
Noworking
newwithKeyword
Interfacing
with the Java APIs and
Java Streams
UsinginPython
to create
There's no new keyword
Pythonand
as Java
thereSwing
is in Java,
C++,GUIs
and Visual Basic. Therefore, the
example
Working with SQL and JDBC(TM)

>>> chap1 = chapter()


Python and Java applets
is equivalent to the following in Java, C++, and Visual Basic, respectively:
In addition, the book contains instructions for downloading and installing the Python
language
and=thenew
Java Development
Kit (JDK). Terminology, definitions, explanations,
chapter
chap1
chapter();
and numerous code samples make this book a useful learning experience.

chapter *chap1 = new chapter();


Whether you are a sophisticated computer user new to programming or a serious
application
developer,
Python Programming with the Java(TM) Class Libraries will
Dim chap1
As New
chapter
give you insight into the power of Python and the know-how to put it to work.

or
Dim chap1 As chapter
Set chap1 = New chapter

777

Here's how we access


the members
of chap1
: the Java
Python
Programming
with

Class Libraries: A Tutorial for Building


Web and Enterprise Applications with Jython
chap1.title
By Richard Hightower

>>>
'Organizing your program'

Publisher: Addison Wesley

>>> chap1.toc Pub Date: June 28, 2002


['Introduction', 'Modules', 'Functions', 'Packages', 'Classes']
ISBN: 0-201-61616-5
>>> Table
chap1.number_of_pages
of
Pages: 640
20 Contents
richness
expression,
and So,
concise
Python
has
Note that all of theseCharacterized
attributes are by
theease
sameofasuse,
those
of the of
chapter
class.
is thesyntax,
instance
of chapter
remained
a
premier
programming
language
for
more
than
a
decade,
and
is
used
by
the same as chapter itself? Let's see using the is identity operator.
novices and professionals alike. In particular, its close relationship to Java(TM) makes
two languages, when used in combination, ideal for Web and distributed enterprise
>>> chap1 is the
chapter
application
development.
0
tutorial
begins with, coverage
of some
thesame
basics
of Python
Using
Okay, chap1 is notThis
the same
as chapter
even though
it hasofthe
attributes.
Orprogramming.
does it? We know
that
plenty
of
skill-building
exercises
and
interactive
programming
sessions,
this
book
dir() lists the attributes of a module and a class. It also lists the attributes of an instance, so let's use will
it to solve
help those new to programming develop an understanding of concepts and practical
this mystery.
techniques. For experienced programmers, the book demonstrates Python's breadth of
>>> dir (chap1)
capabilities and shows the ways that Python interfaces with Java APIs for professional
[]
application development.

>>> dir (chapter)


Python Programming with
the Java(TM) Class Libraries:
A Tutorial for Building
Web 'toc']
['__doc__', '__module__',
'number_of_pages',
'print_me',
'title',
and Enterprise Applications with Jython covers important topics such as:
It looks like chap1 has no attributes at all, yet when we accessed its attributes we got back the values for
chapter. What happens if we try to change a chap1 attribute? Does the class attribute change?
Fundamental programming concepts, including statements, expressions,
interpreters,
First let's change chap1.title
andand
seecompilers
what the title is.
basics, including
operators, string formatting, namespaces, classes, errors,
>>> chap1.title =Python
"Getting
Started"
and
exceptions
>>> chap1.title
'Getting Started'
Object-oriented programming concepts
Next let's check the value of the chapter class's title.
File input/output

>>> chapter.title
intrinsic functions
'Organizing your Python's
program'
Formatting, parsing,
manipulating
strings
chapter.title and chap1.title
areand
no longer
the same
value. Initially, Python uses the class
attributes for chap1. However, if we change an instance attribute, Python creates an attribute only for the
Interfacing with the Java APIs and working with Java Streams
instance, so we should now have a new attribute in chap1's namespace called title. Let's check this with
thedir() function.
Using Python and Java Swing to create GUIs

>>> dir (chap1) Working with SQL and JDBC(TM)


['title']
Python and Java applets
As you can see, there's a new variable called title in chap1's namespace. Just as we thought. However, this
technique works onlyInfor
assigning
Forinstructions
example, iffor
wedownloading
append a string
the tocthe
list,Python
the instance
addition,
the new
bookvalues.
contains
andtoinstalling
doesn't get a new attribute.
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.

>>> chap1.toc.append("Welcome to Python")


>>> chap1.tocWhether
is chapter.toc
you are a sophisticated computer user new to programming or a serious
1
application developer, Python Programming with the Java(TM) Class Libraries will

give you insight into the power of Python and the know-how to put it to work.
Notice that, even after we append a string to toc,chap1.toc and chapter.toc point to the same
object. But what about this:

777

>>> chap1.toc = ["Do not fear", "What is Python", "Why Python"]

>>> chap1.tocPython
is chapter.toc
Programming with the Java Class Libraries: A Tutorial for Building
0
Web and Enterprise Applications with Jython
By Richard Hightower

It shows that assignments change what an instance's member variables refer to.
Publisher: Addison Wesley

Let's wrap up this interactive session.

Pub Date: June 28, 2002

ISBN: 0-201-61616-5
>>> Table
chapter.number_of_pages
is chap1.number_of_pages
of

Pages:
640
1
Contents
>>> dir (chap1)
Characterized by ease of use, richness of expression, and concise syntax, Python has
['title', 'toc']

remained a premier programming language for more than a decade, and is used by
This shows that, since
number_of_pages
was In
never
assigneditsa close
valuerelationship
in chap1, to
theJava(TM)
chapter
and
novices
and professionals alike.
particular,
makes
chap1 attributes fortheit two
pointlanguages,
to the same
object
(they're
actually theideal
samefor
reference).
also shows
that chap1
when
used
in combination,
Web and Itdistributed
enterprise
has the title and application
toc attributes
in its namespace but not number_of_pages.
development.
This tutorial begins with coverage of some of the basics of Python programming. Using
Constructor (__init__)
plenty of skill-building exercises and interactive programming sessions, this book will
help those
new toisprogramming
develop
an isunderstanding
of constructed.
concepts andIt's
practical
The__init__ method,
if present,
called when an
instance
first created or
the
techniques.
For
experienced
programmers,
the
book
demonstrates
Python's
breadth ofis
constructor, and its arguments are the same ones passed to the class constructor expression. __init__
capabilities
and shows
thevariables.
ways that Python interfaces with Java APIs for professional
usually used to define
(i.e., initialize)
instance
application development.
For example, this class constructor expression passes the title argument to __init__ :
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
chap1 = chapter(title="Introduction")
Let's define our chapter class with a constructor that takes three arguments for each instance variable. Notice
Fundamental
programming
concepts,
including
that we've removed the class
variables and
are using only
instance
variables.statements,
(Compareexpressions,
this example, book1.py,
interpreters, and compilers
to our earlier example, book.py.)

class chapter: Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
""" Document
String for chapter class """
Object-oriented programming concepts

def __init__(self, title="", numPages=0, toc=[]):


self.numPages = numPages
File input/output
self.title = title
self.toc
toc functions
Python's=intrinsic
def print_me(self):
parsing,+and
strings
print Formatting,
self.title
" manipulating
" + `self.numPages`
for section in self.toc:
Interfacing
Java APIs and working with Java Streams
print
" "with
+ the
section
Using Python
and Java
to create GUIs
Here we've defined a constructor
that initializes
allSwing
of an instance's
attributes. Note that chapter's constructor
uses default arguments to initialize the member variables. Remember that the self argument refers to the
Working with SQL and JDBC(TM)
current instance.
Python
and Java applets
Below we create an instance
of chapter
and set its title to Getting started. When calling a
constructor, you don't pass a value for the positional self argument.
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development
Kit (JDK). Terminology, definitions, explanations,
>>> chap1 = chapter("Getting
started")
and
numerous
code
samples
make
this
book a useful learning experience.
>>> chap1.print_me()

Getting started
0
Whether you are a sophisticated computer user new to programming or a serious
application
developer,
Python
Programming
with the Java(TM)
Class
will
Next we create an instance
of chapter
and set
its title
to Fundamentals
, its number
of Libraries
pages to 20
, and its
give
you
insight
into
the
power
of
Python
and
the
know-how
to
put
it
to
work.
table of contents to Literals ,Types, and Lists.

>>> chap2 = chapter("Fundamentals", 20, ["Literals", "Types", "Lists"])


>>> chap2.print_me()
Fundamentals 20

777

Literals Python Programming with the Java Class Libraries: A Tutorial for Building
Types
Web and Enterprise Applications with Jython
Lists
By Richard Hightower
Now we create an instance
of chapter with the title Operators and set the table of contents to String
Publisher: Addison Wesley
operators and Arithmetic.
Pub Date: June 28, 2002

ISBN: 0-201-61616-5
>>> Table
chap3
of = chapter(toc=["String operators", "Arithmetic"],title="Operators")

Pages:
>>> Contents
chap3.print_me() 640
Operators 0
Characterized by ease of use, richness of expression, and concise syntax, Python has
String operators
remained a premier programming language for more than a decade, and is used by
Arithmetic

novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
Destructor (__del__)
application development.

The__del__ method
the destructor,
which
is called
class
instance
is about
to be destroyed.
Thisistutorial
begins with
coverage
ofwhen
somethe
of the
basics
of Python
programming.
Using

plenty of skill-building exercises and interactive programming sessions, this book will

class chapter:
help those new to programming develop an understanding of concepts and practical
""" Document String for chapter class """

techniques. For experienced programmers, the book demonstrates Python's breadth of


capabilities and shows the ways that Python interfaces with Java APIs for professional
def __init__(self, title="", numPages=0, toc=[]):
application development.

self.numPages = numPages
self.title
= title with the Java(TM) Class Libraries: A Tutorial for Building Web
Python Programming
self.toc
=
toc Applications with Jython covers important topics such as:
and Enterprise

def __del__(self):
Fundamental programming concepts, including statements, expressions,
print "Leaving"
interpreters, and compilers

def print_me(self):
Python basics,
operators, string formatting, namespaces, classes, errors,
print self.title
+ "including
" + `self.numPages`
and
exceptions
for section in self.toc:
print "
" + section
Object-oriented programming concepts

chap = chapter() File input/output


chap.print_me()
del chap
Python's intrinsic functions
Formatting,
and manipulating strings
Encapsulation with
Privateparsing,
Variables
Interfacing with the Java APIs and working with Java Streams
One of the things that separate classes from records or structures in other languages is the concept of
encapsulation. Encapsulation
hides
the implementation
of your
class and in doing so reduces code
Using
Python
and Java Swingdetails
to create
GUIs
coupling. Coupling is bad.
Working with SQL and JDBC(TM)
Let's say, for example, that you create a simple address book class that downloads all of the addresses from a
corporate database and stores
themand
in aJava
list called
Python
appletsnames. Other programmers who use your class simply access
this names list.
In addition, the book contains instructions for downloading and installing the Python
Well, imagine that the
company
has just landed
some major
accountsdefinitions,
and is hiringexplanations,
more
language
andyou
thework
Java for
Development
Kit (JDK).
Terminology,
employees. Now youand
want
to change
your
addressmake
bookthis
class
to work
withlearning
a middleware
server that connects to
numerous
code
samples
book
a useful
experience.
the database and helps you cache addresses based on usage and changes. You also want to provide a dictionaryWhether
you arelist.
a sophisticated
computer
useryou
newchange
to programming
a serious
like object to work with
the names
You do all this,
but when
the names or
over
to the dictionary
application
developer, Python
Programming
withisthe
Java(TM)
Libraries
will
object, all the other company
programmers'
code stops
working. This
coupling,
andClass
you can
see why
it's bad.
give you insight into the power of Python and the know-how to put it to work.
To reduce coupling you want to hide the implementation details of your class and provide a well-defined
interface to outside users. Private variables and private methods allow you to do this because they aren't visible
outside the class in which they're defined.

777

A well-defined interface
to your
class is a collection
ofJava
public Class
methods
for classAaccess,
but for
it prohibits
Python
Programming
with the
Libraries:
Tutorial
Buildingaccess to
the private variables Web
to limit
theEnterprise
number of Applications
things that canwith
go wrong.
Consider if everyone had access to every
and
Jython
variable in your classthe
number
of potential problems would be staggering. By limiting variable access to
By Richard
Hightower
well-defined methods, you better control the internal state of your class and minimize such problems. If
something does go wrong,
you're more
likely
to know which method to fix.
Publisher:
Addison
Wesley
Pub Date: June 28, 2002

What all this comes down to is good code organization. Packages allow you to organize your modules, on the
ISBN: 0-201-61616-5
Table
of
basis of
functionality
or services, so that you don't run into naming conflicts with other programmers.
Pages: 640

Contents

There's no keyword to declare a variable or method as private. Rather, you prepend a double underscore to the
Characterized
ease of (module
use, richness
of expression, and concise syntax, Python has
variable or method name.
Here's anby
example
book2.py):
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
class chapter:
the two
languages,
when
used in combination,
ideal for Web and distributed enterprise
""" Document
String
for
chapter
class """
application development.

def __init__(self, title="", numPages=0, toc=[]):


This tutorial
begins with coverage of some of the basics of Python programming. Using
self.__numPages
= numPages
plenty
of
skill-building
self.__title = title exercises and interactive programming sessions, this book will
help those
self.__toc
= new
tocto programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
def print_me(self):
application development.
print self.__title
+ " " + `self.__numPages`

for section in self.__toc:


Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
print "
" + section
and Enterprise Applications with Jython covers important topics such as:

Below we define the three instance variables as private, which means that they can't be viewed with the dir()
function.
Fundamental programming concepts, including statements, expressions,

interpreters, and compilers

>>> from book1 import chapter


>>> dir (chapter)Python basics, including operators, string formatting, namespaces, classes, errors,
['__doc__', '__module__',
and exceptions 'print_me']
Object-oriented programming concepts

Packages

File input/output
Packages are a way of organizing Python modules and a way to prevent one programmer from stomping on the
module of another. You assign
a module
to afunctions
package with the form Package_Name.Module_Name.
Python's
intrinsic
Thus, the module name mystuff.sys indicates a module named sys in a package named mystuff.
Formatting, parsing, and manipulating strings
Packages are essentially directories that contain a special __init__.py file to indicate to Python that the directory
Interfacing
thewhen
Java APIs
and working
JavaLet's
Streams
it's dealing with is a package.
This filewith
is used
the package
is firstwith
loaded.
create our own package and
call it package1/__init__.py.
Using Python and Java Swing to create GUIs
First we create a directory called package1. Then we create a file named __init __.py with one Python statement
Working
with SQL, and
and save
JDBC(TM)
that prints "Hello from
package1"
it to the package1 directory. Next we create a module
calledmodule1 in package1 and put in it a Python statement that prints "hello from module1 in
Python and Java applets
package1". In module1, we define one do-nothing function and one do-nothing class named class1 that
contains a do-nothing
named
method1
Inmethod
addition,
the book
contains. instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
Here'spackage1/__init__.py.
and numerous code samples make this book a useful learning experience.

print "Hello from package1"

Whether you are a sophisticated computer user new to programming or a serious


application developer, Python Programming with the Java(TM) Class Libraries will
Here'spackage1/module1.py:
give you insight into the power of Python and the know-how to put it to work.

print "hello from module1 in package1"

777

def function1():
pass

class class1:Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

def method1():
pass

Publisher: Addison Wesley

Pub Date:
June is28,
Make sure that the package1
directory
in 2002
the module search path. Then move out of package1 and fire up the
ISBN:
0-201-61616-5
JythonTable
interpreter.
of

Contents

Pages: 640

>>> from package1.module1 import class1


Hello from package1
Characterized by ease of use, richness of expression, and concise syntax, Python has
hello from module1
package1
remained ain
premier
programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes

>>> dir()
the two languages, when used in combination, ideal for Web and distributed enterprise
['__name__', application
'class1']
development.
Here we see that theThis
codetutorial
in __init__.py
and module1
we load
class1
.
begins with
coverageisofexecuted
some of when
the basics
of Python
programming.
Using
plenty of skill-building exercises and interactive programming sessions, this book will
Now exit and restarthelp
the Jython
interpreter
and try this:
those new
to programming
develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
>>> import package1
capabilities and shows the ways that Python interfaces with Java APIs for professional
Hello from package1
application development.

>>> dir()
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
['__name__', and
'package1']
Enterprise Applications with Jython covers important topics such as:
>>> dir(package1)
Fundamental programming
concepts, including statements, expressions,
['__file__', '__name__',
'__path__']
interpreters, and compilers

>>> vars(package1)
Python basics, including operators, string formatting, namespaces, classes, errors,
{'__file__': 'C:\\python\\book\\chap5\\.\\package1\\__init__.py'
and exceptions
, '__path__': ['.\\package1'],
'__name__': 'package1'}
Object-oriented
programming
conceptsis executed. Look at the package's namespace.
Notice that, when we import
the package, its
__init__.py module
(Remember that the vars command is like the dir command except that it lists the namespace's names and
File input/output
values.)
Python's intrinsic functions
Within__init__.py you can define a list called __all__, which is used with package import* to tell
Python to import all modules
in this package.
Python imports
Formatting,
parsing,Actually,
and manipulating
stringsall modules listed in the package's
__all__ list, so if you want to import a module with the * command, you have to put it in __all__.
Interfacing with the Java APIs and working with Java Streams
Packages can have subpackages. These are subdirectories under the package with __init__.py modules. Since
__init__.py is part of the package,
the package
canSwing
containtoanything
that you find in a regular module, such as
Using Python
and Java
create GUIs
classes and functions.
Working with SQL and JDBC(TM)

Globals and thePython


Global
Statement
and Java
applets
In addition,
instructionsprogrammers
for downloading
installing
the Python for
The word "global" strikes
fear inthe
thebook
heartscontains
of object-oriented
(andand
structured
programmers,
language
and the
Java Developmentthat
Kitare
(JDK).
Terminology,
definitions,
explanations,
that matter). That's because
global
variablesvariables
in a global
namespace
(one that's
available to all
and
numerous
code
samples
make
this
book
a
useful
learning
experience.
modules, functions, and classes)are usually a bad thing and should be avoided.
Whether
you are
a sophisticated
computer
user new
or a of
serious
In fact, there aren't any
real global
variables
in Python.
All variables
havetotoprogramming
be in the context
a module, class,
application
developer,
Python Programming
with the
Java(TM)
Libraries between
will
or function. However,
Python does
have a global
statement, which
allows
you to Class
share variables
you insight into the power of Python and the know-how to put it to work.
functions in the samegive
module.
Here's an example that has two functions and a module-level variable:

var = "hi"

777

#module level variable

Python Programming with the Java Class Libraries: A Tutorial for Building
def sayHi1():
Webvar
and Enterprise Applications with Jython
print
By Richard Hightower

def sayHi2():
Addison Wesley
print Publisher:
var
Pub Date: June 28, 2002

def sayHiMom():
ISBN: 0-201-61616-5
Table of
var
=
var
+ 640
" Mom"
Pages:
Contents
print var

Characterized by ease of use, richness of expression, and concise syntax, Python has
BothsayHi1 and sayHi2
but programming
sayHiMom doesn't.
Tofor
make
workayou
haveand
to import
remained work,
a premier
language
moreit than
decade,
is usedthe
byvar
variable into the functions'
global command
like this: to Java(TM) makes
noviceslocal
and namespaces,
professionalsusing
alike.the
In particular,
its close relationship
the two languages, when used in combination, ideal for Web and distributed enterprise
var = "hi" #module
level variable
application development.

...
...

This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
def sayHiMom():
help those new to programming develop an understanding of concepts and practical
global var techniques. For experienced programmers, the book demonstrates Python's breadth of
var = var + "capabilities
Mom" and shows the ways that Python interfaces with Java APIs for professional
print var
application development.
There's nothing wrong
with Programming
using the global
statement
to import
module-level
variables
a function's
Python
with the
Java(TM)
Class Libraries:
A Tutorial
forinto
Building
Web
namespace.
and Enterprise Applications with Jython covers important topics such as:

Summary

Fundamental programming concepts, including statements, expressions,


interpreters, and compilers
In this chapter, we learned about the benefits and methods of organizing your code. We explained namespaces,
Python
basics, including
operators,
stringclasses,
formatting,
errors, the
code blocks, and working with
namespaces
for modules,
functions,
and namespaces,
methods. Weclasses,
also discussed
exceptions
import statement, whichand
allows
you to import objects from one module to another, and the global
statement, which allows you to import module-level variables into a local namespace.
Object-oriented programming concepts
File input/output

CONTENTS

Python's intrinsic functions


Formatting, parsing, and manipulating strings
Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs
Working with SQL and JDBC(TM)
Python and Java applets
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
CONTENTS
Web and Enterprise Applications with Jython
By Richard Hightower

Chapter 6. Object-Oriented
Programming
Publisher: Addison Wesley
Pub Date: June 28, 2002

What Is OOP? ISBN: 0-201-61616-5


Table of
Objects and Classes
Pages: 640
Contents
Special Class Methods
Inheritance Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
Polymorphism
novices and professionals alike. In particular, its close relationship to Java(TM) makes
Summary the two languages, when used in combination, ideal for Web and distributed enterprise

application development.
Terms in This Chapter
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty
of skill-building exercises and interactive
programming
sessions, this book will
Aggregation/containment
Getter/Setter
m ethods
help those new to programming develop an understanding of concepts and practical
techniques.
the book demonstrates
Python's breadth of
Attribute For experienced programmers,Inheritance
(implementation/
capabilities and shows the ways that Pythoninterface)
interfaces with Java APIs for professional
Cardinality development.
application
Instance
Class Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
Python
Instantiation
and Enterprise Applications with Jython covers
important topics such as:
Class hierarchy
Late-bound polymorphism
Code reuse
Fundamental programming concepts, including statements, expressions,
Multiple inheritance
interpreters, and compilers
Cohesion
Objectformatting, namespaces, classes, errors,
Python basics, including operators, string
Coupling
and exceptions
Replaceability
Encapsulation
Object-oriented programming concepts
Specialization
First class
object
File input/output
Typed polymorphism
Garbage
collection
Python's
intrinsic functions
This chapter explains the fundamentals
of object-oriented
programming,
Formatting, parsing,
and manipulating
strings as well as why it's important and how to
do it in Python.
Interfacing with the Java APIs and working with Java Streams

What Is OOP?

Using Python and Java Swing to create GUIs

Working
andorganizing
JDBC(TM)
Object-oriented programming
(OOP)with
is a SQL
tool for
your programs into reusable objects. It won't
necessarily make you program better or faster, yet it's one of the best ideas in programming to come along so far.
Python and Java
applets is that it's hard to learn and that you should learn a nonA common myth about object-oriented
programming
OOP language first, but you don't have to do this. In fact, OOP is easy to learn because it models the real world.
In addition,
the book
contains instructions for downloading and installing the Python
Bottom line? Don't fear
object-oriented
programming.
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous
Here are the triple pillars
of OOP: code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
Polymorphismapplication developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.
Encapsulation
Inheritance

777

Of the three, polymorphism is the most important because it supports the replaceable nature of objects.

Python Programming with the Java Class Libraries: A Tutorial for Building
Web Boxes
and Enterprise
Applications with Jython
Objects as Black
(Encapsulation)
By Richard Hightower

Say you're driving along and a young child racing toward his fleeing ball runs right in front of your car. Do you
Publisher:
Wesley your foot reaches for the break pedal.
pause and think about what
to do?Addison
No. Instinctively,
Pub Date: June 28, 2002

Think of the break pedal as ISBN:


the interface
to your car's breaking system. You know how to use it because it's well
0-201-61616-5
Table of

defined,
whether this is your
car or640
one you've rented or borrowed, whether the breaks are drum or antilock. The
Pages:
Contents
details of the system's implementation are encapsulatedthat is, hidden from you. All you need to know is how
to use the interface toCharacterized
the break systemthe
pedal. of expression, and concise syntax, Python has
by ease of break
use, richness
remained a premier programming language for more than a decade, and is used by
What does all this have
to doand
withprofessionals
OOP? A great
deal.
OOP its
youclose
define
classes that
interfaces,
novices
alike.
In With
particular,
relationship
to support
Java(TM)
makes and
you use them to instantiate
Twowhen
classes
with
same interface
used
You can
the twoobjects.
languages,
used
in the
combination,
idealcan
for be
Web
andinterchangeably.
distributed enterprise
organize your program
into many
objects, each of which has a specific role (this is called cohesion). The objects
application
development.
perform their roles in ways that are encapsulated from the rest of the program, which means that you change the
way an object worksThis
and tutorial
keep thebegins
rest ofwith
yourcoverage
programof
intact.
some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
Here are some important
object-oriented
ideas:
help those
new to programming
develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
Coupling is when you change one module or class, and doing so adversely affects another module or class.
application development.
(Some coupling may be necessary.)

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
Cohesion is defining modules and classes that have specific roles. (Cohesion helps to reduce coupling.)
and Enterprise Applications with Jython covers important topics such as:
Encapsulation is hiding the implementation details. In OOP, we hide them behind an interface.

Fundamental programming concepts, including statements, expressions,


Interface, in OOP speak, is a collection of methods associated with a class or module.
interpreters, and compilers
Python basics, including operators, string formatting, namespaces, classes, errors,
Objects and Classes
and exceptions
Objects in the real world are made up of many other objects (in OOP speak this is called aggregation or
Object-oriented programming concepts
containment). For example, a car object contains tire objects, an engine object, a steering system object, a
breaking system object, andFile
so forth.
Organizing a program into a hierarchy of objects helps us conceptualize it.
input/output
Essentially, you break down the program into interrelated objects, which are in turn broken down into other
objects. This is called inheritance.
Python's intrinsic functions
A class is a template for creating
objects
by defining
their behaviorstrings
and attributes. Thus, a car class defines the
Formatting,
parsing,
and manipulating
behaviors of a car, such as
Interfacing with the Java APIs and working with Java Streams
Moving forward or backward
Using Python and Java Swing to create GUIs
Breaking

Working with SQL and JDBC(TM)

Turning

Python and Java applets

It also defines the car's


attributes,the
such
as contains instructions for downloading and installing the Python
In addition,
book
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Make
Model
Color
Year

Whether you are a sophisticated computer user new to programming or a serious


application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Two door or four door

withJust
theasJava
Class
Libraries:
A Tutorial
Building
The car class acts as Python
a genericProgramming
template for cars.
there are
many
cars in the
world, sofor
there
can be many
Web
and
Enterprise
Applications
with
Jython
car objects in your program (this concept is known as object cardinality), but they share attributes and behavior.
Richard
Hightower
So, for example, youBy
can
stop and
start both a Volvo and a Chevy. Think of the class as a cookie cutter and its
objects as the cookies it stamps out. The cookies themselves are the instances of the class.
Publisher: Addison Wesley

The great thing about programming


in Python
(and Java for that matter) is that you don't have to start from
Pub Date: June
28, 2002
scratch. There are lots of general-purpose
classes and modules for doing common things. For example, Python
ISBN: 0-201-61616-5
Table of
has a URL
module that knows
how640
to work with files from FTP and HTTP servers.
Pages:
Contents

Let's review the key Characterized


concepts so far:
by ease of use, richness of expression, and concise syntax, Python has

remained a premier programming language for more than a decade, and is used by
and professionals
In(particular,
A class ( Car)novices
is a template
for defining alike.
objects
Volvo). its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application
development.
Attributes describe
an object's
appearance, state, or quality.
Thishow
tutorial
beginsacts.
with coverage of some of the basics of Python programming. Using
Behavior defines
an object
plenty of skill-building exercises and interactive programming sessions, this book will
Cardinality is help
the number
of instances
of an object
in a an
system.
those new
to programming
develop
understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
Define a Car class in
Python as.and shows the ways that Python interfaces with Java APIs for professional
capabilities
application development.

jython i car.py):

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web

class Car: and Enterprise Applications with Jython covers important topics such as:
make = "?"
model = "?"
Fundamental programming concepts, including statements, expressions,
color = "?"
compilers
running = interpreters,
0 #1 isand
true,
0 is false

Attributes

Python basics, including operators, string formatting, namespaces, classes, errors,


and exceptions

Here we see that the attributes


of Car are defined
by its variables,
Object-oriented
programming
concepts which are indented. We can use this class
template to create car instances.
File input/output

# create an instance of my car


Python'sits
intrinsic
functions
# and display
attributes
myCar = Car()
Formatting,myCar.color,
parsing, and manipulating
strings
print "After Create:",
myCar.make,
myCar.model
Interfacing
with the Javathen
APIs and
working with
Java Streams
# Set myCars
attributes
display
attributes
myCar.color, myCar.make,
myCar.model = "Red", "Ford", "Taurus"
Using Python and Java Swing to create GUIs
print "After set:", myCar.color, myCar.make, myCar.model
The output is

Working with SQL and JDBC(TM)


Python and Java applets

After Create: ? ? ?
After set: Red
Ford the
Taurus
In addition,
book contains instructions for downloading and installing the Python

Behavior

language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.

you are
sophisticated
computer
user Let's
new to
programming
a serious
An object's behaviorWhether
is determined
byamethods
defined
by its class.
return
to the Carorclass
example and
application
developer,
Python
Programming
with
the
Java(TM)
Class
Libraries
will
addstart and stop behavior.
give you insight into the power of Python and the know-how to put it to work.

class Car:
make = "?"
model = "?"
color = "?"

777

running
= 0Programming
#1 is true,
0 is
false
Python
with the
Java
Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython

def start(self):
By Richard Hightower
if self.running == 1:
printWesley
"The car is already running"
Publisher: Addison
else:
Pub Date: June 28, 2002
self.running = 1
ISBN: 0-201-61616-5

Table of
Contents
def

Pages: 640

stop(self):
if self.running
Characterized
by ease of use,==0:
richness of expression, and concise syntax, Python has
print
"The car
is for
already
remained a premier programming
language
more thanstopped"
a decade, and is used by
else:
novices and professionals alike. In particular, its close relationship to Java(TM) makes
self.running
= 0
the two languages,
when used in combination,
ideal for Web and distributed enterprise

application development.
Here are some examples of the Car class methods followed by their output:
This tutorial begins with coverage of some of the basics of Python programming. Using

car = Car()
plenty of skill-building exercises and interactive programming sessions, this book will
car.color = "Red"
help those new to programming develop an understanding of concepts and practical
car.make = "Ford"
techniques. For experienced programmers, the book demonstrates Python's breadth of
car.model ="Taurus"

capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.

# Start the car


car.start() Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
print "After and
Start:",
car.color,
car.make,
car.model,
Enterprise Applications
with Jython
covers important
topics suchcar.running
as:
#Stop the car
Fundamental programming concepts, including statements, expressions,
car.stop()
interpreters,
and compilerscar.make, car.model, car.running
print "After Stop:",
car.color,
PythonRed
basics,
including
operators,
After Start:
Ford
Taurus
1 string formatting, namespaces, classes, errors,
and
exceptions
After Stop: Red Ford Taurus 0
Object-oriented programming concepts

The Python Objects Model

File input/output
Unlike in Java, everything in Python is an objectfunctions, modules, classes, packages, numeric
typeseverything. ObjectsPython's
have an intrinsic
identity, functions
a type, and a value. The type determines the methods and operations
that an object supports. The value can be changeable (dictionaries, classes, lists) or immutable (strings, integers,
Formatting, parsing, and manipulating strings
tuples).
Interfacing
with the
Javainstances
APIs andofworking
Java
You know, for example, that
you can create
many
the samewith
class.
ButStreams
did you know that a class is
itself an object, a first class object, that can be dynamically modified? When you modify the template (class), you
Using Python and Java Swing to create GUIs
in effect modify the class instances not yet created.
Working with SQL and JDBC(TM)
To illustrate, we'll modify the attributes of the Car class for Fords.
Python and Java applets

>>> Car.make, Car.model, Car.color = "Ford", "Taurus", "Red"


In addition, the book contains instructions for downloading and installing the Python
Then we'll create a list of three Ford cars.
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
codeCar(),
samples make
this book a useful learning experience.
>>> ford_carsand=numerous
[Car(),
Car()]
Whether
you are a sophisticated computer user new to programming or a serious
Next we'll print out their
make.
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into
the power of Python and theford_cars[2].make
know-how to put it to work.
>>> ford_cars[0].make,
ford_cars[1].make,

('Ford', 'Ford', 'Ford')

777

Now we use the same technique to create three Hondas.

>>> Car.make,Python
Car.model
= "Honda",
"Civic"
Programming
with the Java
Class Libraries: A Tutorial for Building
>>> honda_cars
[Car(),
Car()]
Web=and
EnterpriseCar(),
Applications
with Jython
>>> honda_cars[0].make,
honda_cars[1].make, honda_cars[2].make
By Richard Hightower
('Honda', 'Honda', 'Honda')
Publisher: Addison Wesley

As you can see, when you


can change the template, you essentially create objects with new attributes.
Pub Date: June 28, 2002
ISBN: 0-201-61616-5

Table of

Special
Class Methods
Pages: 640
Contents

Characterized
by ease for
of use,
richness
of expression,
and concise
syntax,
has
In Python you can define
special methods
classes
that have
special meaning.
You can
also Python
define methods
to
remained
a
premier
programming
language
for
more
than
a
decade,
and
is
used
by
make your class look like other objects such as lists, dictionaries, and tuples.
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
Creating and Destroying
Class Instances
application development.
Like other OOP languages,
Python
has awith
destructor
andofa some
constructor.
A constructor
is called
when anUsing
instance is
This tutorial
begins
coverage
of the basics
of Python
programming.
instantiated. A destructor
when an instance
garbage-collected.
The method
__init__
denotes
plentyisofcalled
skill-building
exercisesisand
interactive programming
sessions,
this book
will the
constructor. The method
the destructor.
help __del__
those new todenotes
programming
develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
Here's the Car classcapabilities
(Car2.py) with
its constructor
and shows
the waysand
thatdestructor:
Python interfaces with Java APIs for professional
application development.

class Car:
make =Python
"?"Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
model and
= Enterprise
"?"
Applications with Jython covers important topics such as:
color = "?"
running = 0 #1 is true, 0 is false
Fundamental programming concepts, including statements, expressions,
def __init__(self,
interpreters, andmake,
compilersmodel, color):

self.make = make
Python basics, =
including
self.model
modeloperators, string formatting, namespaces, classes, errors,
and
exceptions
self.color = color
print "constructor called"
Object-oriented programming concepts

def __del__(self):
File input/output
print "destructor called"
...
Python's intrinsic functions
The __init__ method takes
the formparsing, and manipulating strings
Formatting,

__init__ (self[, Interfacing


args...]):
with the Java APIs and working with Java Streams
The __del__ method takes
the form
Using
Python and Java Swing to create GUIs

__del__ (self): Working with SQL and JDBC(TM)


First we create an instance Python
of the Car
class.applets
Notice that constructorcalled is printed out, because the
and Java
__init__ method is called when we instantiate Car.
In addition, the book contains instructions for downloading and installing the Python
>>> myCar = Car("Ford",
"Taurus",
language and the Java
Development"Red")
Kit (JDK). Terminology, definitions, explanations,
constructor called
and numerous code samples make this book a useful learning experience.
Next we print out theWhether
attributes
that
set when the
constructor
you
arewere
a sophisticated
computer
userwas
newcalled.
to programming or a serious

application developer, Python Programming with the Java(TM) Class Libraries will

>>> myCar.make, myCar.model, myCar.color


give you insight into the power of Python and the know-how to put it to work.
('Ford', 'Taurus', 'Red')

777

Then we try to destroy this instance to see if the destructor is called.

>>> myCar = None

>>> myCar is Python


None Programming with the Java Class Libraries: A Tutorial for Building
1
Web and Enterprise Applications with Jython
>>> None
By Richard Hightower
>>> None
destructor
Publisher: Addison Wesley
Pub Date: June 28, 2002

The destructor isn't called when we assign myCar to None. That's because Car isn't destroyed until it's
ISBN: 0-201-61616-5
Table of
garbage-collected,
which may never happen. For example, the garbage collector may be implemented to run only

Pages: 640
Contents
if there's
no more memory left.

Characterized by ease of use, richness of expression, and concise syntax, Python has

Representing remained
the Class
Instance
as alanguage
Stringfor more than a decade, and is used by
a premier
programming

novices and professionals alike. In particular, its close relationship to Java(TM) makes
There are two methods
string
representations
of an object:
repr
anddistributed
__string
__.
the for
twocreating
languages,
when
used in combination,
ideal__for
Web__and
enterprise
application development.
The __repr__ method represents your object in such a way that it can be recreated with the eval statement.
eval evaluates a string
a Python
expression
and works
much
the interactive
interpreter.
__repr
__ is
This as
tutorial
begins
with coverage
of some
oflike
the basics
of Python
programming.
Using
called when you useplenty
back quotes
or call the exercises
repr command.
Here's programming
what it looks like:
of skill-building
and interactive
sessions, this book will
help those new to programming develop an understanding of concepts and practical
__repr__ (self):
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
The __str__ method is a way to do a nice looking string for printing. It's called by the str() built-in
application development.
function and by the print statement. Here's what it looks like:
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web

__str__ (self):
and Enterprise Applications with Jython covers important topics such as:
We can add __str__ to our Car class like this:

Fundamental programming concepts, including statements, expressions,

class Car:
interpreters, and compilers
...
...
Python basics, including operators, string formatting, namespaces, classes, errors,
def __str__(self):
and exceptions
strRun = ""
if Object-oriented
self.running
== 1:concepts
programming
strRun="\nThe car is running"
File input/output
else:
strRun="\nThe car is stopped"
Python's intrinsic functions

str = "make " + make + \


Formatting, parsing, and manipulating strings
"\nmodel " + model + \
"\ncolor
" APIs
+ color
+ strRun
Interfacing
with the Java
and working
with Java Streams
return str
Using Python and Java Swing to create GUIs
Here's the output (from the Car2.py module) in interactive mode:
Working with SQL and JDBC(TM)

C:\py\book\chap9>jython -i Car2.py
Python and Java applets

>>> car = Car("Ford", "Mustang", "Cherry Red")


constructor called
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,

>>> print carand numerous code samples make this book a useful learning experience.
make Ford
model MustangWhether you are a sophisticated computer user new to programming or a serious
developer, Python Programming with the Java(TM) Class Libraries will
color Cherry application
Red
give you insight into the power of Python and the know-how to put it to work.
The car is stopped
__repr__ can also be used for display. However, if at all possible, it should evaluate to an expression that
returns the object. Thus, if you use the Python eval statement, which reads in text and parses it to an
expression, you should be able to recreate the instance with the string that __repr__ returns.

777

Programming
Here's an example ofPython
__repr
__:

def

with the Java Class Libraries: A Tutorial for Building


Web and Enterprise Applications with Jython
By Richard Hightower
__repr__(self):

format = """Car("%s","%s","%s")"""
return format
% (self.make,
self.model, self.color)
Publisher: Addison
Wesley
Pub Date: June 28, 2002

Here's the output (from the Car2.py


module) in interactive mode:
ISBN: 0-201-61616-5

Table of

Pages: 640

Contents
C:\py\book\chap9>jython
-i Car2.py
>>> car = Car ("Ford", "Mustang", "Midnight Blue")
Characterized by ease of use, richness of expression, and concise syntax, Python has
constructor

remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
>>> print `car`
the two languages, when used in combination, ideal for Web and distributed enterprise
Car("Ford","Mustang","Midnight Blue")
application development.

>>> print carThis tutorial begins with coverage of some of the basics of Python programming. Using
make Ford
plenty of skill-building exercises and interactive programming sessions, this book will
model Mustanghelp those new to programming develop an understanding of concepts and practical
color Midnight
Blue For experienced programmers, the book demonstrates Python's breadth of
techniques.
capabilities and shows the ways that Python interfaces with Java APIs for professional

The car is stopped


application development.
>>> car2 = eval(`car`)
constructor Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

>>> print car2


make Ford
model Mustang

Fundamental programming concepts, including statements, expressions,


interpreters, and compilers

color Midnight Blue


Python basics, including operators, string formatting, namespaces, classes, errors,
The car is stopped

and exceptions
In the above example, we used the return from car.__repr__() in conjunction with the eval statement
programming
concepts
to create car2. The car2Object-oriented
instance has the
same attributes
as the original car instance.
File input/output

Comparing, Hashing, and Truth Testing


Python's intrinsic functions
Three other methods, shown in Table 6-1, have special meaning in Python. We'll use module Car3.py to
Formatting, parsing, and manipulating strings
demonstrate them.

max_Price = 7000 Interfacing with the Java APIs and working with Java Streams
running = 0
Using Python and Java Swing to create GUIs

def __nonzero__(self):
Working with SQL and JDBC(TM)
if (self.price > Car.max_Price):
return
Python0and Java applets
else:
Inreturn
addition, the
1 book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous
code samples make this book a useful learning experience.
def __cmp__(self,
other):
if (self.price > other.price): return 1
Whether you are<a sophisticated
computer return
user new to-1
programming or a serious
if (self.price
other.price):
application developer,
Python Programmingreturn
with the Java(TM)
Class Libraries will
if (self.price
== other.price):
0
give you insight into the power of Python and the know-how to put it to work.

def __hash__(self):
v= self.make + self.model + self.color + `self.price`
return hash(v)

777

def __init__(self,
make, model,
color,
price=5000):
Python Programming
with the
Java Class
Libraries: A Tutorial for Building
self.make
= Enterprise
make
Web and
Applications with Jython
self.model
model
By Richard=Hightower
self.color = color
self.price
= price
Publisher:
Addison Wesley
...
Pub Date: June 28, 2002
...
ISBN: 0-201-61616-5

Table of
Contents

Pages: 640

Table 6-1. Python Class Methods


Characterized by ease of use, richness of expression, and concise syntax, Python has
remained aDescription
premier programming language for more than a decade, and is used by
Method
novices
and
professionals
alike. In particular,
its close
relationship
__cmp__ (self,
Called
by the comparison
operators,
==,=>,
>, <, =<to Java(TM) makes
the
two
languages,
when
used
in
combination,
ideal
for
Web
and distributed enterprise
other)
application development.
__hash__ (self)
Used in conjunction with the hash function to return a 32-bit integer used
for hash values in dictionaries
This tutorial begins with coverage of some of the basics of Python programming. Using
__nonzero__ plenty of skill-building
Used for Boolean
truth
is the
object in a sessions,
true statethis
or book
a false
exercises
andtesting;
interactive
programming
willstate

(self)

help those new to programming develop an understanding of concepts and practical


techniques. For experienced programmers, the book demonstrates Python's breadth of
Here we've added a class
variable
called
max_Price
an instance
variable
called
price
. The
capabilities
and
shows
the ways thatand
Python
interfaces
with Java
APIs
for professional
__nonzero__ method
uses
max_Price
to
see
if
the
price
of
the
instance
is
under
the
maximum
price. The
application development.
__cmp__ method uses the price to compare another Car instance to the current one. The hash is calculated by
creating a large string
representation
of all with
the hash
values of the
individual
attributes
of the
instance.
Python
Programming
the Java(TM)
Class
Libraries:
A Tutorial
forCar
Building
Web
and Enterprise Applications with Jython covers important topics such as:
The following code is also part of Car3.py.

if __name__ == "__main__":
Fundamental programming concepts, including statements, expressions,
car1 = Car("Ford",
"Midnight Blue", 5000)
interpreters, and"Mustang",
compilers
car2 = Car("Chevrolet", "Corvette", "Champagne gold", 9000)
basics, including
operators, string
formatting, namespaces, classes, errors,
#ToPython
demonstrate
compare
__cmp__
and
exceptions
if (car1 > car2):
print car1
Object-oriented programming concepts
else:
print car2
File input/output

#toPython's
demonstrate
Boolean __nonzero__
intrinsic functions
if(car1): print "Buy It"
if(not car2):
print
"Iand
can't
afford
it"
Formatting,
parsing,
manipulating
strings
#toInterfacing
demonstrate
hash
with the Java
APIs __hash__
and working with Java Streams
print `hash(car1)`
Using Python and Java Swing to create GUIs
The output looks like this:

Working with SQL and JDBC(TM)

C:\py\book\chap9>jython car3.py
make Chevrolet Python and Java applets
model Corvette
In addition,
color Champagne
goldthe book contains instructions for downloading and installing the Python
language
The car is stopped and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Buy It
I can't afford it
Whether you are a sophisticated computer user new to programming or a serious
-1273809553
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

Getting, Setting, and Deleting Attributes

777

We can override the default behavior for how objects are displayed, printed, constructed, compared, truth-tested,
and so forth. We can also override how member variables in our instance are accessed. The methods shown in

Table 6-2 customizePython


attributeProgramming
access for classwith
instances.
the Java

Class Libraries: A Tutorial for Building


Web and Enterprise Applications with Jython
By Richard Hightower

Table 6-2. Instance Access Methods


Publisher: Addison Wesley

Method

Definition
ISBN:
0-201-61616-5
__getattr__ (self,
name)
Gets the value of an attribute
Table of

Pages:
640
__setattr__
(self, name, value)
Sets the value of an attribute
Contents
__delattr__ (self, name)
Deletes an attribute
Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
Essentially, you provide getter/setter methods to control access to your member variables. Let's create a version
novices and professionals alike. In particular, its close relationship to Java(TM) makes
of the Car class that controls access to the price attribute so that users can't set the price under $1,000.
the two languages, when used in combination, ideal for Web and distributed enterprise
class Car: application development.
Pub Date: June 28, 2002

...
This tutorial begins with coverage of some of the basics of Python programming. Using
...
plenty of skill-building exercises and interactive programming sessions, this book will
def __setattr__(self, name, value):
help those new to programming develop an understanding of concepts and practical
if name == "price":
techniques. For experienced programmers, the book demonstrates Python's breadth of
if (value > 1000):
capabilities and shows the ways that Python interfaces with Java APIs for professional
self.__dict__["price"] = value
application development.
else:
self.__dict__["price"]
1000for Building Web
Python Programming with
the Java(TM) Class Libraries: A =
Tutorial
else:
and Enterprise Applications with Jython covers important topics such as:
self.__dict__[name] = value
...
Fundamental programming concepts, including statements, expressions,
...
interpreters, and compilers
Notice that we use the __dict__ method that contains all of the member variables of the class instance. If we
Python basics, including
string
formatting,
namespaces,
classes,loop
errors,
had tried to use self.attribute_name
, we operators,
would have
thrown
our program
into an endless
of
and exceptions
recursive calls to __setattr
__ (I know this from experience). The method checks to see if the name of the
attribute is price. If so, we provide some special handling for setting price. Otherwise, we just set the value of
Object-oriented programming
concepts
all other attributes: self.__dict__[name]
= value
, which, by the way, is the behavior of the default
implementation. A similar technique could be used for __getattr__ and __delattr__. The sample code
here uses the above added File
logicinput/output
in the __setattr__ method.
Python's intrinsic
C:\py\book\chap9>jython
-i functions
car4.py
>>> car = Car("Ford",
"Mustang",
"Bright Orange", 5000)
Formatting, parsing, and manipulating strings
>>> car.price = 2000
>>> car.price
Interfacing with the Java APIs and working with Java Streams
2000
Using Python and Java Swing to create GUIs

>>> car.price = 1001


Working with SQL and JDBC(TM)
>>> car.price
1001
Python and Java applets

>>> car.price = 900


In addition, the book contains instructions for downloading and installing the Python
>>> car.price
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
1000
and numerous code samples make this book a useful learning experience.

Inheritance Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give
insight
into code
the power
Python
and theeffect
know-how
putyou
it toimplement
work.
Inheritance allows you
toyou
reuse
common
and soofhas
a profound
on theto
way
your
Python classes. It also allows you to organize your classes into a hierarchical arrangement. Classes toward the
bottom of the hierarchy inherit from classes higher up (like a family tree). Thus, if you create a class, classB,
that inherits behavior and attributes from another class, ClassA, then classB becomes the subclass of
classA, and classA becomes the superclass of classB.

777

Python Programming with the Java Class Libraries: A Tutorial for Building

A subclass can override


or create new behavior and attributes specific to its role. This is called specialization.
Web and Enterprise Applications with Jython
By Richard Hightower

The Limits of Inheritance

Publisher: Addison Wesley


Pub Date: June 28, 2002

ISBN: 0-201-61616-5
It mayoflook like one, but inheritance is no silver bullet. In fact, there are reasons to limit its use.
Table
Pages: 640
Contents
Like all good things, inheritance should be used in moderation, primarily to avoid coupling

between subclass and superclass.


Characterized by ease of use, richness of expression, and concise syntax, Python has
premier programming
language
for more than a decade, and is used by
There are tworemained
forms of ainheritance:
implementation
and interface.
novices and professionals alike. In particular, its close relationship to Java(TM) makes
thethe
twoimplementation
languages, when
ideal we
for try
Web
enterprise
Remember that
of aused
classiniscombination,
one of the things
to and
hidedistributed
with encapsulation.
application
development.
If you're going to do implementation inheritance from a weakly written base class (superclass),
watch outif a base class is buggy, so are all of its subclasses. And, if you introduce a bug into the
This
tutorialitbegins
coverage
of some of the basics of Python programming. Using
base class, you
introduce
into allwith
of the
subclasses.
plenty of skill-building exercises and interactive programming sessions, this book will
those new
toclasses
programming
develop an
of concepts
andwith
practical
I'm not sayinghelp
organizing
your
into a hierarchy
of understanding
classes is wrong;
just proceed
techniques.
For
experienced
programmers,
the
book
demonstrates
Python's
breadth of
caution because inheritance provides code reuse at the expense of encapsulation.
capabilities and shows the ways that Python interfaces with Java APIs for professional
A good book application
on object-oriented
design is Design Patterns (Gamma et al., Addison-Wesley, 1995).
development.
It describes some of the pitfalls of inheritance, including tight coupling of subclasses to
Programming
with
Java(TM)
Libraries:
A Tutorial to
forOOP
Building Web
superclasses, Python
and provides
blueprints
forthe
good
designs.Class
The book
is indispensable
and
Enterprise
Applications
with
Jython
covers
important
topics
such
as:
programmers.

Fundamental
programming concepts, including statements, expressions,
Code Reuse and the
Class Hierarchy
interpreters, and compilers
One of the major advantages of object-oriented programming is code reuse. We'll illustrate this with a real-world
Python basics, including operators, string formatting, namespaces, classes, errors,
example of inheritance.
and exceptions
Cars and trucks are similar in that they both have certain physical characteristics like doors and windows and
Object-oriented programming concepts
they both have a make, model, and vehicle identification number (VIN). Of course, they're also very different.
One is for carrying loads; the
is for carrying passengers. Still, we can put the things common to trucks and
Fileother
input/output
cars in a base class, which we can then subclass into separate car and truck classes
Python's intrinsic functions
Based on these principles we can create a base class called Automobile that consists of make, model, VIN,
price, mpg, and so forth. The
Truck subclass
specialize Automobile
with towing capacity, bed size,
Formatting,
parsing, may
and manipulating
strings
and the like; the Car subclass may do so with trunk capacity and number of passengers.
Interfacing with the Java APIs and working with Java Streams
The class hierarchy for cars and trucks might look like Figure 6-1.
Using Python and Java Swing to create GUIs
Figure 6-1. Automobile Class Hierarchy
Working with SQL and JDBC(TM)

Python and Java applets


In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower
Publisher: Addison Wesley
Pub Date: June 28, 2002

Table of
Contents

ISBN: 0-201-61616-5
Pages: 640

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
with the
Java(TM)
Class
Libraries:
Building
Webclass
Now we'll derive twoPython
classesProgramming
from Automobile
called
Car and
Truck
, as in A
theTutorial
figure. for
Here
is the base
and
Enterprise
Applications
with
Jython
covers
important
topics
such
as:
(fromAutomobile1.py):

class Automobile:
max_Price Fundamental
= 7000 programming concepts, including statements, expressions,
and compilers
running = interpreters,
0
Python basics, including operators, string formatting, namespaces, classes, errors,

def __setattr__(self, name, value):


and exceptions
...
Object-oriented programming concepts

def __nonzero__(self):
...File input/output

Python's intrinsic
functions
def __cmp__(self,
other):
...
...Formatting, parsing, and manipulating strings
Interfacing with the Java APIs and working with Java Streams
def __hash__(self):
...Using Python and Java Swing to create GUIs

def __init__(self,
make,
model, color, price=5000):
Working with SQL
and JDBC(TM)
...
Python and Java applets

def __del__(self):
In addition,
the book contains instructions for downloading and installing the Python
...
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
def start(self):
...
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
def stop(self):
give
you insight into the power of Python and the know-how to put it to work.
...

777

def __str__(self):
...

def __repr__(self):
Python Programming with the Java Class Libraries: A Tutorial for Building
...
Web
and Enterprise Applications with Jython
By Richard Hightower

Here are the Car and Truck subclasses (from Automobile2.py):


Publisher: Addison Wesley

class Car (Automobile):


Pub Date: June 28, 2002
def __init__(self,
make, model, color, price, trunk_space= 5):
ISBN: 0-201-61616-5
Automobile.__init__(self,
make, model, color, price)
Table of

Pages: 640
self.trunk_space
= trunk_space
Contents
Characterized by ease of use, richness of expression, and concise syntax, Python has
class Truck (Automobile):

remained a premier programming language for more than a decade, and is used by
novices and professionals
alike. In
particular,
its close relationship
Java(TM) makes = 2):
def __init__(self,
make,
model,
color,
price, to
tow_capacity
theAutomobile.__init__(self,
two languages, when used in combination,make,
ideal formodel,
Web and distributed
color, enterprise
price)
application
development.
self.tow_capacity = tow_capacity

ThisCar
tutorial(Automobile)
begins with coverage
some of
basicsa of
Python
Using .
The statement class
tellsofPython
to the
subclass
Car
classprogramming.
from Automobile
plenty
of
skill-building
exercises
and
interactive
programming
sessions,
this
book
willPython
The statement Automobile.__init__(self, make, model, color, price) tells
help
those
new
to
programming
develop
an
understanding
of
concepts
and
practical
to call the base class constructor. The constructor isn't doing much right now, but when we build graphical user
For experienced programmers, the book demonstrates Python's breadth of
interfaces it will do atechniques.
lot.
capabilities and shows the ways that Python interfaces with Java APIs for professional
application
When you create a new
instancedevelopment.
of the Truck class, you get the attributes defined in it as well as all attributes
defined in its base class, Automobile. Thus, the base classes and current classes mix to assemble a template
with is
theinitialized
Java(TM)with
Class
A Tutorial
for Building
for the class instance.Python
Then Programming
each class instance
theLibraries:
attribute data
that describes
it. Web
and Enterprise Applications with Jython covers important topics such as:
Methods work similarly. An instance can access all of the methods of its class and its superclasses (base classes).
If you call a method on an instance, Python checks its class for that method definition. If it finds it, it calls the
Fundamental programming concepts, including statements, expressions,
method. If not, it checks the superclass (or superclasses). Python will look all the way up the class hierarchy for
interpreters, and compilers
the method to call, so when you define a method with the same name as that of a base class method, you
effectively override that method's
Python functionality.
basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
Python, unlike Java, provides multiple inheritance, which means that it can inherit functionality from more than
one class. Java provides single
inheritance, programming
which means concepts
that a class can inherit only from one superclass.
Object-oriented
There are problems with multiple
inheritance. For example, two base classes can have a method with the same
File input/output
name. Python gets rid of these problems by having left-to-right multiple inheritance. That is, the base class to the
left in the definition of the Python's
class overrides
thefunctions
base class to the right.
intrinsic
Let's say that our Car classFormatting,
inherits from
two base
Automobile
and Vehicle. Let's also say that
parsing,
and classes,
manipulating
strings
both of these classes have a __start__ method. If we want Car to use Vehicle's __start__ method, we
have to define it like this: Interfacing with the Java APIs and working with Java Streams

Python and Java Swing to create GUIs


def Car (Vehicle,Using
Automobile):
Working with's SQL
and JDBC(TM)
If we want Car to use Automobile
__start
__ method, we have to define it like this:
Python and
Java applets
def Car (Automobile,
Vehicle):
In addition, the book contains instructions for downloading and installing the Python

Polymorphism
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Of the three pillars of OOP, inheritance and encapsulation are nice to have but polymorphism is the true key to
Whether you
areobjects
a sophisticated
newoftoall:
programming
or a serious
OOP's success. Polymorphism
gives
the mostcomputer
importantuser
feature
replaceability.
application developer, Python Programming with the Java(TM) Class Libraries will
There are two formsgive
of polymorphism:
late-bound
typed. Visual
uses late-bound,
you insight into
the powerand
of Python
and theBasic
know-how
to put it towhereas
work. Java uses
typed. Python polymorphism is a hybrid of the two.

777

Late-Bound Polymorphism

In Python, late-boundPython
polymorphism
means that
can appear
to beAother
objects
their class
Programming
withclass
the instances
Java Class
Libraries:
Tutorial
forifBuilding
implements special methods.
becauseApplications
a function is with
an object,
a class can act like a function just by
Web andThus,
Enterprise
Jython
implementing a special
method.Hightower
Numeric types are also objects, so with special methods a class can act like a
By Richard
numeric type.
Publisher: Addison Wesley

For example, to make aPub


classDate:
act like
a function we can use the function notation with the class to make a call
June 28, 2002
and pass instances of the class where we expect a function object. All we need to do is add a __call__ method
ISBN: 0-201-61616-5
to a class
in of
the form __call__(self[, args]. The following interactive session shows how:
Table

Contents

Pages: 640

>>> class hello:


Characterized
by ease of use, richness of expression, and concise syntax, Python has
...
def __call__(self):
remained
a
premier
language for more than a decade, and is used by
...
print programming
"Hello World"
novices
and
professionals
alike.
In
particular, its close relationship to Java(TM) makes
...
the
two
languages,
when
used
in
combination,
ideal
for Web and distributed enterprise
>>> hi = hello()
# define an instance of
hello
application
development.
>>> hi()
# use the hi instance as a function
Hello World

This tutorial begins with coverage of some of the basics of Python programming. Using
plenty ofnumber
skill-building
exercises
programming
sessions, this book will
Also, we can use a variable
of arguments
withand
theinteractive
__call__
method as follows:
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
>>> class Add:
capabilities
and shows the ways num1,
that Python
interfaces with Java APIs for professional
...
def __call__(self,
num2):
applicationreturn
development.
...
num1 + num2

...
Python Programming
Java(TM) Class
A Tutorial
>>> add = Add()
#definewith
antheinstance
of Libraries:
the Add
classfor Building Web
and
Enterprise
Applications
with
Jython
covers
important
topics
such as:
>>> add(1,2)
# use the add instance as a function
3
Fundamental programming concepts, including statements, expressions,
We can define classes that act like numeric types with the __add__, __radd__, __sub__, and __rsub__
interpreters, and compilers
methods. The method used depends on the class, as shown in Table 6-3. To demonstrate how we use them, let's
define a simple Car class Python
that implements
__add__.
Follow along
in interactive
mode.
basics, including
operators,
string formatting,
namespaces,
classes, errors,
and exceptions

>>> class Car:


...
def Object-oriented
__init__(self,
inventory):
programming
concepts
...
self.inventory = inventory
...
def File
__add__(self,
other): #define an __add__ method
input/output
...
return self.inventory + other
Python's intrinsic functions
...
>>> #define a Car instance to hold the # of buicks
parsing, and manipulating strings
>>> buicks_in_lotFormatting,
= Car(5)
with the
APIs the
and working
Java Streams
>>> #define a CarInterfacing
instance
toJava
hold
# of with
chevys
>>> chevys_in_lotUsing
= Car(20)
Python and Java Swing to create GUIs
Table
6-3. Methods
That
Define Classes to Act Like Numbers
Working
with SQL and
JDBC(TM)

Python and Java applets


In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Method

Behavior
Python Programming with the Java Class Libraries: A Tutorial
for Building
Web
and
Enterprise
Applications
with
Jython
(self, other), __radd__ (self, other)
>> num1 + num2
By Richard Hightower

__add__
__sub__ (self, other), __rsub__ (self, other)
>> num1 - num2
__mul__ (self,Publisher:
other),
__rmul__ (self, other)
>> num1 * num2
Addison Wesley
__div__ (self,Pub
other),
(self, other)
>> num1 / num2
Date: June__rdiv__
28, 2002
__mod__ (self, other),
__rmod__ (self, other)
>> num1 % num2
ISBN: 0-201-61616-5
Table of

Pages:
640
__divmod__
(self, other), __rdivmod__ (self, other) >> divmod(num1, num2)
Contents
__pow__ (self, other), __rpow__ (self, other)
>> num1 ** num2
Characterized by ease of use, richness of expression, and concise syntax, Python has
__lshift__ (self,
other),
__rlshift__
(self,
other)
>>and
num1
remained a premier programming language for more than a decade,
is used<<
by num2
__rshift__ (self,
other),
__rrshift__
(self,
>>to Java(TM)
num1 >>makes
num2
novices and
professionals
alike. In particular,
its close other)
relationship
the
two
languages,
when
used
in
combination,
ideal
for
Web
and
distributed
enterprise
__and__ (self, other), __rand__ (self, other)
>> num1 & num2
application
development.
__xor__ (self, other), __rxor__ (self, other)
>> num1 ^ num2
__or__ (self,
__ror__
(self,
other)
num1 | num2
Thisother),
tutorial begins
with coverage
of some
of the basics of Python>>
programming.
Using
plenty of skill-building exercises and interactive programming sessions,
this book
__neg__ (self)
>> num1
= 1will
help those new to programming develop an understanding of concepts
and practical
>> -num1
techniques. For experienced programmers, the book demonstrates-1
Python's breadth of
capabilities and shows the ways that Python interfaces with Java >>
APIsnum1
for professional
__pos__ (self)
= 1
application development.
>> +num1
1
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
__abs__ (self)
= -1
and Enterprise Applications with Jython covers important topics >>
such num1
as:
>> abs(num1)
1
programming #
concepts,
expressions,
>>> buicks_in_lotFundamental
+ 5
if weincluding
add 5statements,
more...how
many buicks?
interpreters, and compilers
10
>>> chevys_in_lot + 5
# if we add 5 more; how many chevys?
Python basics, including operators, string formatting, namespaces, classes, errors,
25
and exceptions

Now we can add numeric types to our instances.


Object-oriented programming concepts
What about adding other instances? For example, what happens if we add chevys_in_lot +
File input/output
buicks_in_lot?

intrinsic functions
>>> chevys_in_lotPython's
+ buicks_in_lot
Traceback (innermost
last):
Formatting, parsing, and manipulating strings
File "<interactive input>", line 0, in ?
File "<interactive
input>",
line
in __add__
Interfacing
with the Java
APIs 5,
and working
with Java Streams
TypeError: __add__ nor __radd__ defined for these operands
Using Python and Java Swing to create GUIs
Of course, this isn't what we want. To get the proper behavior we need to define a __radd__ method, which is
necessary when the operand
is on thewith
rightSQL
andand
the left
operand doesn't support __add__. To add both instances
Working
JDBC(TM)
together, we have to do this (follow along):
Python and Java applets

>>> class Car:


Indef
addition,
the book contains instructions
for downloading and installing the Python
...
__init__(self,
inventory):
language and
the Java Development=Kitinventory
(JDK). Terminology, definitions, explanations,
...
self.inventory
and
numerous
code samples make
this book a useful learning experience.
...
def
__add__(self,
other):
...
return self.inventory + other
Whether
you are a sophisticated other):
computer user new to programming or a serious
...
def __radd__(self,
application
developer,
Python
Programming
Java(TM) Class Libraries will
...
return self.inventorywith
+ the
other
give
you
insight
into
the
power
of
Python
and
the
know-how
to put it to work.
...
>>> buicks_in_lot, chevys_in_lot = Car(5), Car(20)
>>> chevys_in_lot + buicks_in_lot
25

777

If you define the methods


shown
in Table 6-4,
youthe
canJava
create aClass
class Libraries:
whose instances
act like
dictionary. Let's
Python
Programming
with
A Tutorial
fora Building
create such a class that
implements
all of the
methods in the
table
and calls a real dictionary.
Web
and Enterprise
Applications
with
Jython
By Richard Hightower

class MyDict:
def __init__(self):
Publisher: Addison Wesley
self.dict
= {}
Pub Date: June 28, 2002
def __len__(self):
ISBN: 0-201-61616-5
return len(self.dict)
Table of

Pages: 640
Contents
def __getitem__(self, key):
return self.dict[key]
Characterized by ease of use, richness of expression, and concise syntax, Python has
def __setitem__(self, key, value):
remained a premier programming language for more than a decade, and is used by
self.dict[key]=value
novices and professionals alike. In particular, its close relationship to Java(TM) makes
def __delitem__(self, key):
the two languages, when used in combination, ideal for Web and distributed enterprise
del(self.dict[key])
application development.
def keys(self):
return
This
tutorial self.dict.keys()
begins with coverage of some of the basics of Python programming. Using
def values(self):
plenty of skill-building exercises and interactive programming sessions, this book will
return
self.dict.values()
help
those new
to programming develop an understanding of concepts and practical
def items(self):
techniques. For experienced programmers, the book demonstrates Python's breadth of
return and
self.dict.items()
capabilities
shows the ways that Python interfaces with Java APIs for professional
def has_key(self,
key):
application development.
return self.dict.has_key(key)
def get(self,
key):with the Java(TM) Class Libraries: A Tutorial for Building Web
Python Programming
return
self.dict.get(key)
and
Enterprise
Applications with Jython covers important topics such as:
def clear(self):
self.dict.clear()
Fundamental programming concepts, including statements, expressions,
def copy(self):
interpreters,
and compilers
return
self.dict.copy()
def __str__(self):
Pythonstr(self.dict)
basics, including operators, string formatting, namespaces, classes, errors,
return
and
exceptions
def __repr__(self):
return
repr(dict)
Object-oriented programming concepts
def update(self, dict):
self.dict.update(dict)
File input/output
Python's intrinsic functions
Table 6-4. Methods That Define Classes to Act like Dictionaries
Formatting, parsing, and manipulating strings
Method

Behavior
Interfacing with the Java
APIs and working with Java Streams

__len__(self)
>> len(dict) 3
Using
Python
and
Java
Swing
to create GUIs
__getitem__(self, key)
>>
dict[key]
'Missy'
__setitem__(self,
key,with
value)
>>JDBC(TM)
dict[key] = value
Working
SQL and
__delitem__(self, key)
>> del dict[key]
Python and Java applets
keys(self)
>> dict.keys() ['Miguel', 'Adam', 'Rick']
values(self)In addition, the book contains>>
dict.value()
['Martha',
instructions
for downloading
and installing'Missy',
the Python
'Kiley']
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
items(self) and numerous code samples >>
[('Rick',
'Kiley'),
makedict.items()
this book a useful learning
experience.
('Adam', 'Missy'), ('Miguel', 'Martha')]
Whether
user new to programming
or a serious
has_key(self,
key)you are a sophisticated
>> computer
dict.has_key(key)
1
application developer, Python Programming with the Java(TM) Class Libraries will
get(self, key)
>>> dict.get('Rick') 'Kiley'
give you insight into the power of Python and the know-how to put it to work.
clear(self)
>>dict.clear()
copy(self)
>>cdict = dict.copy()
update(self, dict)
>>dict2.update(dict)

777

To test the dictionary,


we write
the followingwith
code:the Java
Python
Programming

Class Libraries: A Tutorial for Building


Web and Enterprise Applications with Jython
==
"__main__":
By Richard
Hightower

if __name__
main()

Publisher: Addison Wesley

def main():
Pub Date: June 28, 2002
dict = MyDict()
ISBN: 0-201-61616-5
print
"test __setitem__"
Table
of

Pages: 640
Contents
dict["Ham"] = "Eggs"
dict["Tom"] = "Jerry"
Characterized by ease of use, richness of expression, and concise syntax, Python has
dict["Mike"] ="Ike"
remained a premier programming language for more than a decade, and is used by
print "setitem ", dict

novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
print "test __getitem__ and get"
application development.

print "getiem ", dict["Ham"], dict["Tom"], dict["Mike"]


print "get
", dict.get("Ham"),
dict.get("Tom"),
dict.get("Mike")
This tutorial
begins with coverage of some
of the basics of Python programming.
Using
plenty of skill-building exercises and interactive programming sessions, this book will

print "test
help thosedel"
new to programming develop an understanding of concepts and practical
del dict["Ham"]
techniques. For experienced programmers, the book demonstrates Python's breadth of
print dict
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.

print "test keys"


for keyPython
in Programming
dict.keys():
with the Java(TM) Class Libraries: A Tutorial for Building Web
print
" "Applications
+ key with Jython covers important topics such as:
and
Enterprise
print "test values"
Fundamental
programming concepts, including statements, expressions,
for value in
dict.values():
interpreters,
compilers
print
" " +and
`value`
basics, including operators, string formatting, namespaces, classes, errors,
print "testPython
items"
and
exceptions
for item in dict.items():
print
" " + `item`
Object-oriented programming concepts

print "testFilehas_keys"
input/output
print "true " + `dict.has_key("Tom")`
print "false
" +intrinsic
`dict.has_key("Ham")`
Python's
functions
print "testFormatting,
copy" parsing, and manipulating strings
cdict = dict.copy()
print cdictInterfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs

print "test clear"


dict.clear()
Working with SQL and JDBC(TM)
print dict
Python and Java applets

print "test update"


dict.update(cdict)
In addition, the book contains instructions for downloading and installing the Python
print cdict
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
We put the code we use to test the dictionary in the section of the module that runs only as a main module. That
Whether you are a sophisticated computer user new to programming or a serious
is,
application developer, Python Programming with the Java(TM) Class Libraries will
>>> import dict
give you insight into the power of Python and the know-how to put it to work.

>>> dict.main()
test __setitem__
setitem {'Tom': 'Jerry', 'Mike': 'Ike', 'Ham': 'Eggs'}
test __getitem__ and get

777

getitem Eggs Python


JerryProgramming
Ike
with the Java Class Libraries: A Tutorial for Building
get Eggs Jerry
WebIke
and Enterprise Applications with Jython
test del
By Richard Hightower
{'Tom': 'Jerry', 'Mike': 'Ike'}
test keys
Publisher: Addison Wesley
Tom
Pub Date: June 28, 2002
Mike
ISBN: 0-201-61616-5
Table
of
test
values

Pages: 640
Contents
'Jerry'
'Ike'
Characterized by ease of use, richness of expression, and concise syntax, Python has
test items remained a premier programming language for more than a decade, and is used by
('Tom', 'Jerry')
novices and professionals alike. In particular, its close relationship to Java(TM) makes
('Mike', 'Ike')
the two languages, when used in combination, ideal for Web and distributed enterprise
test has_keysapplication development.
true 1
false 0
This tutorial begins with coverage of some of the basics of Python programming. Using
test copy
plenty of skill-building exercises and interactive programming sessions, this book will
{'Tom': 'Jerry',
'Mike':
'Ike'} develop an understanding of concepts and practical
help those
new to programming
test clear techniques. For experienced programmers, the book demonstrates Python's breadth of
{}
capabilities and shows the ways that Python interfaces with Java APIs for professional
test update application development.
{'Tom': 'Jerry', 'Mike': 'Ike'}
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
As promised, our dictionary
class acts
just like a regular
dictionary.
and Enterprise
Applications
with Jython
covers important topics such as:
To find out more about how to simulate built-in objects, refer to the documentation that ships with Python. It's a
Fundamental programming concepts, including statements, expressions,
wealth of well-written information.
interpreters, and compilers

Python basics, including operators, string formatting, namespaces, classes, errors,


andThe
exceptions
Power of Polymorphism
Object-oriented programming concepts
The dictionary we created is simple; it only delegates operations to a real dictionary object.
Imagine building a dictionary-like
class that accesses a file, a database, or a directory server. To the
File input/output
application developer, this class looks just like another dictionary but does far more. You can even
use it like a class instance
transparently,
with code written to work with built-in dictionaries. This
Python's
intrinsic functions
is truly a powerful concept.
Formatting, parsing, and manipulating strings
To write a class whose instances behave like a list, you implement the methods __getslice__(),
Interfacing with the ,Java
APIs and,count()
working with
Java Streams
__setslice__(),__delslice__()
append()
,index()
,insert() ,pop(),
remove() ,reverse()
, and sort(), just like you do with Python standard list objects. For
Using Python and Java Swing to create GUIs
concatenation you use __add__() and __radd__().
Working with SQL and JDBC(TM)
Python and Java applets

Python's List and Dictionary Modules


In addition, the book contains instructions for downloading and installing the Python
language
and the
Java Development
(JDK).
Terminology,
explanations,
Python ships with
two class
modules,
userdict andKit
userlist,
that
implement adefinitions,
dictionary and
a list,
and
numerous
code
samples
make
this
book
a
useful
learning
experience.
respectively. Both are well documented.
Whether you are a sophisticated computer user new to programming or a serious
We won't implementapplication
a list in thisdeveloper,
section. As
an exercise
at the end
of the
create
a list using
Python
Programming
with
the chapter,
Java(TM)you'll
Class
Libraries
will a
technique similar to give
the one
we
used
for
a
dictionary.
you insight into the power of Python and the know-how to put it to work.

Typed Polymorphism

777

With OOP you can build an entire framework of extensible reusable components. Python, unlike other

languages, isn't strictly


typed.Programming
In Java, Visualwith
Basic,
andJava
C++, Class
classesLibraries:
become types
that thefor
userBuilding
can make into
Python
the
A Tutorial
objects (i.e., instances),
whereas
in Python Applications
all instances ofwith
a class
are of type Instance ; also, classes aren't
Web
and Enterprise
Jython
types unto themselves
are part
of a type class. The following examples illustrate these ideas.
Bybut
Richard
Hightower
First we define a simplePublisher:
class, Myclass
.
Addison Wesley
Pub Date: June 28, 2002
>>> class Myclass:
ISBN: 0-201-61616-5
... Tablepass
of

Pages:
640
... Contents

Characterized
by ease and
of use,
richness
of expression, and concise syntax, Python has
Then we create an instance
of Myclass
check
its type.
remained a premier programming language for more than a decade, and is used by
>>> an_instance
= and
Myclass()
novices
professionals alike. In particular, its close relationship to Java(TM) makes
>>> type(an_instance)
the two languages, when used in combination, ideal for Web and distributed enterprise
<jclass org.python.core.PyInstance
at 5325988>
application development.
Next we check the type
Myclass
. with coverage of some of the basics of Python programming. Using
Thisoftutorial
begins
plenty of skill-building exercises and interactive programming sessions, this book will
>>> type(Myclass)
help those new to programming develop an understanding of concepts and practical
<jclass org.python.core.PyClass
at 7914640>
techniques. For experienced programmers,
the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
Programmers, if you're
used to other
languages that use typed classes, you may think that Python is a little weird.
application
development.
Actually, the typed system of other languages is orthogonal to Python's. The only real difference is a little bit of
syntax and the fact that
in Python
classes don't
types. Class Libraries: A Tutorial for Building Web
Python
Programming
withdefine
the Java(TM)
and Enterprise Applications with Jython covers important topics such as:
For example, in Java you do this to get the type of a class:

an_instance.getClass().getName()
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
whereas in Python you do this:
Python basics, including operators, string formatting, namespaces, classes, errors,
an_instance.__class__.__name__
and exceptions
Again, in Java you do this Object-oriented
to see if an objectprogramming
is an instanceconcepts
of a class:

if(an_instance instanceof
File input/outputMyClass)System.out.println("true");
In Python you do this:

Python's intrinsic functions

if(isinstance(an_instance,
MyClass)):
print("true")
Formatting, parsing,
and manipulating
strings
In Python, classes and instances
are objects
thatJava
can APIs
be manipulated
at runtime,
is a good thing. For
Interfacing
with the
and working
with Javawhich
Streams
instance, you can add a method to a class at runtime so that every instance of that class has that method available
in its interface. Also, you can
addPython
members
an instance
runtime.
Whether those members are methods or
Using
andtoJava
Swing toatcreate
GUIs
other objects doesn't matter, because everything is an object that can be manipulated. This makes Python very
Working with SQL and JDBC(TM)
flexible.

and Java applets


So, why have a section on Python
typed polymorphism
if Python doesn't really support it? Actually, Python has
something very close. For example, you can check to see if an instance is a class type like this:
In addition, the book contains instructions for downloading and installing the Python
if isinstance(an_instance,
MyClass)Kit (JDK). Terminology, definitions, explanations,
language and the Java Development
and numerous code samples make this book a useful learning experience.
Let's go back to our earlier example of cars and trucks with a function that takes a list of automobiles and starts
Whether you are a sophisticated computer user new to programming or a serious
each one.
application developer, Python Programming with the Java(TM) Class Libraries will
def startAuto(list):
give you insight into the power of Python and the know-how to put it to work.

for auto in list:


if isinstance(auto, Automobile):
auto.start()

777

The function invokesPython


the __start
__ method
of each
auto Class
instance
in the list.
doesn't for
careBuilding
if the instance is
Programming
with
the Java
Libraries:
A It
Tutorial
aCar or a Truck because
any
instance ofApplications
either is also with
an instance
of Automobile and thus supports the
Web and
Enterprise
Jython
__start__ method.
This is the
form of polymorphism most people with a Java background are used to.
By Richard
Hightower
The __start__ method
works not only with the Car and Truck subclasses but also with any future
Publisher: Addison Wesley
subclass that inherits from Automobile, such as Motorcycle.
Pub Date: June 28, 2002

Table of

Summary
Contents

ISBN: 0-201-61616-5
Pages: 640

Characterized
by ease ofof
use,
richness of expression,
and concise
syntax, Python
has and
In this chapter we covered
the fundamentals
object-oriented
programming:
polymorphism,
inheritance,
remained
a
premier
programming
language
for
more
than
a
decade,
and
is
used
by
encapsulation. We also looked at typed and late-bound polymorphism.
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
CONTENTS
application development.
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
Object-oriented programming concepts
File input/output
Python's intrinsic functions
Formatting, parsing, and manipulating strings
Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs
Working with SQL and JDBC(TM)
Python and Java applets
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
CONTENTS
Web and Enterprise Applications with Jython
By Richard Hightower

Chapter 7. Errors
and Exceptions
Publisher: Addison Wesley
Pub Date: June 28, 2002

Syntax and Sequence


ISBN:Errors
0-201-61616-5
Table of
The Danger of Exceptions
Pages: 640
Contents
The try Statement
Characterized by ease of use, richness of expression, and concise syntax, Python has
The raise Statement
a premier programming language for more than a decade, and is used by
Classes andremained
Instances
as Exceptions
novices and professionals alike. In particular, its close relationship to Java(TM) makes
Getting the the
Most
Out
of
Your
Exceptions
two languages,
when
used in combination, ideal for Web and distributed enterprise
Summary application development.

Terms in This Chapter


This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
Call stack
finally clause
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities
and shows
the ways
that PythonGranularity
interfaces with Java APIs for professional
Catchall bucket,
exception
handler
application development.
catch statement
Most to least specific order
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and
Enterprise
Applications with Jython covers
Class-based
exception
raise important
statement topics such as:
else clause
Throwing versus raising
Fundamental programming concepts, including statements, expressions,
Error interpreters, and compilers
try block

formatting, namespaces, classes, errors,


exceptPython
clause basics, including operators, string
try statement
and exceptions
Exception
Suite
Object-oriented programming concepts
Exception class
User-defined versus built-in
File input/output
exception
Exception handling
Python's intrinsic functions
Bad things happen to good programs: Disks crash, files are corrupted, and batteries fail. Such things are typically
manipulating
more the exception than theFormatting,
rule, and toparsing,
plan forand
all of
them wouldstrings
make for some very complicated code. That's
why modern programming languages like Python have the ability to handle bad things, called exceptions in
Interfacing with the Java APIs and working with Java Streams
programming speak.
Using
Javathe
Swing
createofGUIs
The old way of dealing with
errorsPython
was toand
check
returntotypes
functions, but this was very time consuming.
Each function call would require an if statement with perhaps many elif clauses; code would have to be
Working with SQL and JDBC(TM)
written to extract what had happened. The new way is exception handling, in which the exception has the
information about what went
wrong.
of checking after each of the method calls, you can set up one
Python
andInstead
Java applets
exception handler that works with many methods.
In addition, the book contains instructions for downloading and installing the Python
By the end of this chapter,
youand
should
understand
try,raise
, andTerminology,
finally statements.
should also
language
the Java
Development
Kit (JDK).
definitions,You
explanations,
have a firm grasp onand
the numerous
class-based
exceptions
that
Python
defines.
A
class-based
exception
allows
you to
code samples make this book a useful learning experience.
create a hierarchy of exception classes.
Whether you are a sophisticated computer user new to programming or a serious
application developer,
Python Programming with the Java(TM) Class Libraries will
Syntax and Sequence
Errors
give you insight into the power of Python and the know-how to put it to work.
If you followed along with the interactive sessions in previous chapters as recommended, you ran into errors,
most of them involving syntax (I know I have). Here's an example:

777

>>> for x in xrange(0, 100)

... TracebackPython
(innermost
last):
Programming
with the Java Class Libraries: A Tutorial for Building
(no code object)
at lineApplications
0
Web and Enterprise
with Jython
File "<stdin>",
1
By Richardline
Hightower
for x in xrange(0, 100)
^
Publisher: Addison Wesley
SyntaxError: invalid
syntax
Pub Date: June 28, 2002
ISBN: 0-201-61616-5

UsingSyntaxError:
invalid syntax as a clue, we discover that we forgot to put the colon at the
Table of

Pages: 640
end ofContents
the for header. There's not much you can do about syntax errors except fix them. As you learn Python,
you'll see such errors less and less.
Characterized by ease of use, richness of expression, and concise syntax, Python has
remained
premier
programming
for more than a decade, and is used by
Perhaps some readers
have runa into
exceptions
like thislanguage
one:
novices and professionals alike. In particular, its close relationship to Java(TM) makes
>>> list = 1 the two languages, when used in combination, ideal for Web and distributed enterprise
>>> for x in application
list: development.

...
print(`x`)
This tutorial begins with coverage of some of the basics of Python programming. Using
...
plenty of skill-building
Traceback (innermost
last):exercises and interactive programming sessions, this book will
help
those
new
programming
File "<stdin>", lineto1,
in ? develop an understanding of concepts and practical
techniques.
For
experienced
programmers, the book demonstrates Python's breadth of
AttributeError: __getitem__

capabilities and shows the ways that Python interfaces with Java APIs for professional
development.
Here we tried to use application
an integer like
a sequence, and, by throwing an exception, Python is telling us we can't do
that.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise
Applications
with Jython
coversand
important
topics
such as: An error usually
Before we go any further,
I should clear
up the difference
between
error and
an exception.
involves syntax, such as a missing comma, whereas an exception usually involves an operation gone wrong, such
as dividing by zero. Think of it this way: Exceptions can be correct syntax but wrong operations.
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers

The Danger of Exceptions

Python basics, including operators, string formatting, namespaces, classes, errors,


and exceptions
An unhandled exception can stop a program dead in its tracks. This may be okay if you're still developing it, but
it's bad if the program has been
delivered. Consider
the following
Object-oriented
programming
concepts function (from divby()-1.py), which stops as
soon as it runs into a 0 value as a denominator in the list.
File input/output

def figurePercentage(figures):
for tuple in
figures:
Python's
intrinsic functions
numerator = tuple[0]
denominator
= tuple[1]
Formatting, parsing,
and manipulating strings
percent = numerator/denominator
the Java APIs is
and working
with Java Streams
printInterfacing
("The with
percentage
" + `percent`)
Using Python and Java
Swingtotoreceive
create GUIs
Here the function figurePercentage()
expects
a sequence of sequences that each contain
two numeric fields. So we create a list sequence that contains several tuples, each containing two numeric
Working with SQL and JDBC(TM)
values, and we invoke figurePercentage()
with the sequence as follows:

Python and Java


applets 200.0), (300.0, 400.0), (1.0, 0.0), (11.0,20.
figures = [(10.0,20.0),
(100.0,
figurePercentage(figures)
In addition, the book contains instructions for downloading and installing the Python
language and function
the Java iterates
Development
Kiteach
(JDK).
definitions,
ThefigurePercentage()
through
tupleTerminology,
in the list, extracting
its 0explanations,
-indexed item as
and
numerous
code
samples
make
this
book
a
useful
learning
experience.
the numerator and its 1-indexed item as the denominator.
you are a sophisticated computer user new to programming or a serious
for tuple in Whether
figures:
application
developer, Python Programming with the Java(TM) Class Libraries will
numerator = tuple[0]
give
you
insight
into the power of Python and the know-how to put it to work.
denominator = tuple[1]
percent = numerator/denominator
percent = percent * 100
print ("The percentage is " + `percent` + "%")

777

One tuple has a 0.0Python


denominator,
and we know
can'tClass
divideLibraries:
any number
by zero. Let's
run this and see
Programming
with that
the we
Java
A Tutorial
for Building
what happens.
Web and Enterprise Applications with Jython
By Richard Hightower

>>> import divby0_1


The percentage Publisher:
is 50.0%
Addison Wesley
The percentage Pub
isDate:
50.0%
June 28, 2002
The percentage is 75.0%
ISBN: 0-201-61616-5
Traceback
Table of (innermost last):

Pages: 640
Contents
File
"<stdin>", line 1, in ?
File "C:\\.\divby0_1.py", line 10, in ?
Characterized by ease of use, richness of expression, and concise syntax, Python has
File "C:\\.\divby0_1.py", line 5, in figurePercentage
remained a premier programming language for more than a decade, and is used by
ZeroDivisionError: float division
novices and professionals alike. In particular, its close relationship to Java(TM) makes
>>>

the two languages, when used in combination, ideal for Web and distributed enterprise
development.
The function stops asapplication
soon as it hits
the zero denominator because a ZeroDivisionError exception has
occurred.

This tutorial begins with coverage of some of the basics of Python programming. Using
plenty
of skill-building
exercises
interactive
will
One way to solve such
a problem
is to prevent
it fromand
happening.
Weprogramming
can do this bysessions,
checkingthis
forbook
a zero
help
those
new
to
programming
develop
an
understanding
of
concepts
and
practical
denominator before we divide the numerator by the denominator. In a lot of C and older C++ programs that
techniques.
experienced
programmers,
book
demonstrates
Python's
breadth as
of an
predate exception handling,
this For
is exactly
what you
have to do. the
(We'll
cover
when to handle
a problem
capabilities
and
shows
the
ways
that
Python
interfaces
with
Java
APIs
for
professional
exception and when to check beforehand for possible errors later in the chapter.)
application development.
But what if we don't expect to get a zero value in the denominator? What if this value is an exceptional
Python
Programming
withthing
the Java(TM)
Class
Libraries:
Tutorial
for Building
occurrence? If we add
tests for
every possible
that can go
wrong,
our codeA can
become
messy andWeb
hard to
and
Enterprise
Applications
with
Jython
covers
important
topics
such
as:
read. Conversely, if we don't handle this error, our program will just stop working when it receives a zero
divisor. Mission-critical programs aren't supposed to stop working for minor problems like this. What if this is a
function in a payroll program?
Would you
want to get paid
late because
someone
forgot
to check for a divide-byFundamental
programming
concepts,
including
statements,
expressions,
zero exception?
interpreters, and compilers
Python basics, including operators, string formatting, namespaces, classes, errors,
The try Statement
and exceptions

Thetry statement specifies


a way to handle
exceptions. concepts
One form is the following:
Object-oriented
programming

try:

File input/output

suite
except expression-target:
Python's intrinsic functions
suite
Formatting, parsing, and manipulating strings
except:
suite
Interfacing with the Java APIs and working with Java Streams
which can have one or many except clausesthe exception handlers. If an exception occurs in the try
Python and
Javathat
Swing
create
GUIs
clause's suite of statements,Using
an exception
handler
besttofits
it will
be invoked. An except clause that
doesn't have an expression target can act as a catchall bucket. If an exception doesn't have a specific
Working with SQL and JDBC(TM)
exception handler and an except clause without an expression target is present, the exception will go to that
clause.
Python and Java applets
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
Themake
Call
and numerous code samples
this Stack
book a useful learning experience.
Whether you
are a sophisticated
computer
new toif programming
a serious
A call stack represents
the order
of called functions.
Foruser
example,
a module callsorfunction
A()
application
developer,
Python
Programming
withfunction
the Java(TM)
Class
will
and function A()
calls function
B()
and function
B() calls
C(), the
callLibraries
stack is Ayou insight
into
powerC()
of Python
andhandled,
the know-how
to put to
it to
work. B().
>B->C. If angive
exception
occurs
in the
function
and isn't
it propagates
function
If function B() doesn't handle it, the exception propagates to function A(). If function A()
doesn't handle it, the program stops.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

Matching a Handler to an Exception


Publisher: Addison Wesley

Unlike in Java, inPub


Python
no 2002
common base class such as Throwable,
Date:there
Juneis28,
RuntimeException
,
or
Exception
for all exceptions. Even so, Python has generally
ISBN: 0-201-61616-5
Table
of the Java approach to exception handling, as we'll see later.
adopted
Pages: 640
Contents

Similar to Java's
way, in Python
an exception
matches
handler if and
the handler
the object
thathas
Characterized
by ease
of use, richness
of aexpression,
conciseissyntax,
Python
identifies the remained
exception aorpremier
a base programming
class of the exception,
or
if
the
object
thrown
exactly
matches
language for more than a decade, and is used bythe
handler's object
identity.
novices and professionals alike. In particular, its close relationship to Java(TM) makes

the two languages, when used in combination, ideal for Web and distributed enterprise
Also, in Python the handler matches the exception if it has a tuple containing an item that matches
the exception.application
This meansdevelopment.
that you can handle several exceptions in one except clause.
This tutorial begins with coverage of some of the basics of Python programming. Using
Here is figurePercentage()
(fromexercises
divby0-2.py)
exception sessions,
handling:this book will
plenty of skill-building
and expanded
interactivewith
programming
help those new to programming develop an understanding of concepts and practical
def figurePercentage(figures):
techniques. For experienced programmers, the book demonstrates Python's breadth of
for tuple
in figures:
capabilities
and shows the ways that Python interfaces with Java APIs for professional
try:
application development.

numerator = tuple[0]

denominator
tuple[1]
Python Programming
with the =
Java(TM)
Class Libraries: A Tutorial for Building Web
percent
= numerator/denominator
and Enterprise
Applications
with Jython covers important topics such as:
percent = percent * 100
print ("The percentage is " + `percent` + "%")
Fundamental
programming concepts, including statements, expressions,
except
ZeroDivisionError:
interpreters,
compilers
printand
("percentage
error")

Python basics,
including operators,
string
formatting,400.0),
namespaces,(1.0,
classes, errors,
figures = [(10.0,20.0),
(100.0,
200.0),
(300.0,
0.0), (11.0,20.
and
exceptions
figurePercentage(figures)
The output looks like this: Object-oriented programming concepts

File input/output
>>> import divby0_2
The percentage is 50.0%
Python's intrinsic functions
The percentage is 50.0%
The percentage isFormatting,
75.0% parsing, and manipulating strings
percentage error
The percentage isInterfacing
55.0% with the Java APIs and working with Java Streams
The percentage is 55.0%
Using Python and Java Swing to create GUIs
>>>
Working with SQL and JDBC(TM)

The except Clause

Python and Java applets


Notice that the program in the example above doesn't stop midway in its iteration through the list. Instead, it
In addition,
bookofcontains
instructions
for downloading
and installing
Python
prints out that there was
an error the
in one
the percentage
calculations
and continues
on its way.the
The
magic to
this is the try statement
withand
the the
except
clause. Kit (JDK). Terminology, definitions, explanations,
language
Java Development
and numerous code samples make this book a useful learning experience.

try:
numerator
tuple[0]
Whether=you
are a sophisticated computer user new to programming or a serious
denominator
tuple[1]
application=developer,
Python Programming with the Java(TM) Class Libraries will
percent
give =younumerator/denominator
insight into the power of Python and the know-how to put it to work.
print ("The percentage is " + `percent`)
except ZeroDivisionError:
print ("percentage error")

777

In English this says, Python


"Try to execute
these statements.
the ZeroDivisionError
exception
occurs, go to
Programming
with the If
Java
Class Libraries: A Tutorial
for Building
theexcept clause Web
and execute
its statement."
This handling
the exception allows the program to continue.
and Enterprise
Applications
withof
Jython
By Richard Hightower

What if someone passes a list that doesn't have just sequences? Follow along in interactive mode.
Publisher: Addison Wesley

>>> from divby0_2 import figurePercentage


June 28, 2002
>>> nasty_list Pub
= Date:
[(1.0,
1.0), (2.0, 2.0), 2, (3.0, 3.0)]
ISBN: 0-201-61616-5
>>> Table
figurePercentage(nasty_list)
of

Contents

Pages: 640

Here's the output:

Characterized by ease of use, richness of expression, and concise syntax, Python has

The percentage
is 1.0
remained
a premier programming language for more than a decade, and is used by
The percentage
is and
1.0
novices
professionals alike. In particular, its close relationship to Java(TM) makes
Traceback (innermost
last):
the two languages,
when used in combination, ideal for Web and distributed enterprise
File "<stdin>",
line
1, in ?
application
development.
File "C:\\.\divby0_2.py", line 19, in ?
This tutorial begins with coverage
of some
the basics of Python programming. Using
File "C:\\.\divby0_2.py",
line 4,
in of
figurePercentage
plenty
of
skill-building
exercises
and
interactive
programming sessions, this book will
AttributeError: __getitem__
help those new to programming develop an understanding of concepts and practical
Even though we handled
the divide-by-zero
problem,
we didn't the
handle
thedemonstrates
AttributeError
exception.
techniques.
For experienced
programmers,
book
Python's breadth
of So
we add an exceptcapabilities
clause withand
an empty
expression
to catch
this and
anyJava
other
possible
exceptions.
shows target
the ways
that Python
interfaces
with
APIs
for professional
application development.
The Catchall Exception Handler
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
andpercentages
Enterprise and
Applications
with Jython
covers
important topics
as: to
Let's continue figuring
add the ability
to handle
a nonsequence
beingsuch
passed

figurePercentage(). The following example is from divby0_3.py.


Fundamental programming concepts, including statements, expressions,

def figurePercentage(figures):
interpreters, and compilers
for tuple in figures:
try:Python basics, including operators, string formatting, namespaces, classes, errors,
numerator = tuple[0]
and exceptions
denominator = tuple[1]
percent programming
= numerator/denominator
Object-oriented
concepts
percent = percent * 100
File input/output
print ("The percentage is " + `percent` + "%")
except ZeroDivisionError:
Python's
intrinsic
functions by 0 percentage error")
print
("divide
except:
Formatting,
and manipulating
strings
printparsing,
("percentage
error")
print("The nice list")
Interfacing with the Java APIs and working with Java Streams
figures = [(10.0,20.0), (100.0, 200.0), (300.0, 400.0), (1.0, 0.0), (11.0,20.
figurePercentage(figures)
Using Python and Java Swing to create GUIs
print("-")
Working with SQL and JDBC(TM)
print("The nasty list")
Python1.0),
and Java(2.0,
applets 2.0), 2, (3.0, 3.0)]
nasty_list = [(1.0,
figurePercentage(nasty_list)
In addition, the book contains instructions for downloading and installing the Python
language
and the the
Java
Development
Kit (JDK).
explanations,
This time when we run
our program,
error
is caught. Note
that weTerminology,
changed the definitions,
exception handler
of the
and numerous
codetosamples
make
book
a useful learning
experience.
ZeroDivisionError
exception
print that
therethis
was
a divide-by-zero
error.
The catchall exception
handler prints out that there was a generic percentage error as before. Here's the output:
Whether you are a sophisticated computer user new to programming or a serious
The nice listapplication developer, Python Programming with the Java(TM) Class Libraries will
give is
you insight
The percentage
50.0%into the power of Python and the know-how to put it to work.

The percentage is 50.0%


The percentage is 75.0%
divide by 0 percentage error
The percentage is 55.0%

777

The percentage
is Programming
55.0%
Python
with the Java Class Libraries: A Tutorial for Building
-
Web and Enterprise Applications with Jython
By Richard Hightower

The nasty list


The percentage Publisher:
is 100.0%
Addison Wesley
The percentage Pub
isDate:
100.0%
June 28, 2002
percentage error ISBN: 0-201-61616-5
of
The Table
percentage
isPages:
100.0%
640
Contents

In essence, the catchall exception handler


Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
except:
novices and professionals
alike. In particular, its close relationship to Java(TM) makes
print ("percentage
error")
the two languages, when used in combination, ideal for Web and distributed enterprise
application
says, "If any exception
is raised, development.
catch it and print out "percentage error"." To highlight that this
statement is a catchall exception, let's send figurePercentage() another list, this time with a sequence
This
tutorial
begins with
coverage
of some of the basics of Python programming. Using
that contains only one
item
(this example
is from
divby0_3.py).
plenty of skill-building exercises and interactive programming sessions, this book will
help thoseimport
new to programming
develop an understanding of concepts and practical
>>> from divby0_3
figurePercentage
techniques.
For
experienced
programmers,
the book demonstrates Python's breadth of
...
capabilities
and
shows
the
ways
that
Python
interfaces with Java APIs for professional
...
application development.
>>> list1 = [[0,0],
[1,1], [2,2], [3], [4,4]]

>>> figurePercentage(list1)
Python Programming
with the Java(TM) Class Libraries: A Tutorial for Building Web
divide by 0 percentage
error
and
Enterprise
Applications
with Jython covers important topics such as:
The percentage is 100%
The percentage is 100%
percentage error Fundamental programming concepts, including statements, expressions,
The percentage isinterpreters,
100% and compilers
list[3] is a list with only
one item
in including
it, so we get
an IndexError
exception
when weclasses,
try to get
the
Python
basics,
operators,
string formatting,
namespaces,
errors,
denominator.

and exceptions

Generally it's a bad idea to Object-oriented


sprinkle catchallprogramming
exception handlers
throughout your code. However, instead of a
concepts
hard and fast rule this is more an issue of style and application specifics. For instance, if you expect a zero in the
denominator from time to time,
you should test for this rather than rely on catching it as an exception. The same
File input/output
is true if you expect an occasional integer instead of a sequence in a list.
Python's intrinsic functions
Because we added exception handling for zero denominators, we're saying that we don't expect them, but if we
Formatting, parsing, and manipulating strings
add the check

if(denominator ==Interfacing
0): with the Java APIs and working with Java Streams
print ("The percentage cannot be calculated")
Using Python and Java Swing to create GUIs
elif:
percent = numerator/denominator
Working with* SQL
percent = percent
100and JDBC(TM)
print ("ThePython
percentage
is " + `percent` + "%")
and Java applets
we're saying that we In
doaddition,
expect them.
the book contains instructions for downloading and installing the Python

language and the Java Development Kit (JDK). Terminology, definitions, explanations,
Using exception handling is a matter of program requirements; in other words, it's application specific.
and numerous code samples make this book a useful learning experience.
Exception handling is expensive and should be used only in exceptional cases, not in the normal execution of
code. Remember, though,
youyou
should
put go code
(for beginners,
code" is code or
essential
to running
Whether
are anever
sophisticated
computer
user new"go
to programming
a serious
the program) in an exception
handler.
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

Exception Handling and Interfacing with Other


Systems
Publisher: Addison Wesley
Pub Date: June 28, 2002

The

When you interface with other systems, such as components you didn't write, nonstandard libraries,
ISBN: 0-201-61616-5
Table
of
or, worse,
end users, the chances of an exception happening that you can't plan for increase. As I
Pages: 640
Contents
said, one uncaught exception can bring down the whole program, so just before deployment put
catchall exception handlers in your code where this interfacing will take place. (At a minimum, the
Characterized by ease of use, richness of expression, and concise syntax, Python has
catchall should be able to log the error or you should be able to enable logging with problematic
remained a premier programming language for more than a decade, and is used by
code to catch exceptions.)
novices and professionals alike. In particular, its close relationship to Java(TM) makes
theatwo
languages,
when
used in
combination,
ideal foraWeb
and distributed
enterprise
You don't want
catchall
exception
handler
when
you're developing
program.
Rather, you
want
application
development.
to identify and handle as many exceptional conditions as needed, especially for mission-critical
systems. To avoid a harmless exception bringing down such a system, log all exceptions and
This tutorial begins with coverage of some of the basics of Python programming. Using
evaluate them offline or try to recreate them in a controlled setting and develop a handler for them.
plenty of skill-building exercises and interactive programming sessions, this book will
You may be able to recover from some exceptions gracefully.
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
else Clause
application development.

Another feature of the first form of the try statement is the else clause. else's suite is executed only if no
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
exceptions occurred.
and Enterprise Applications with Jython covers important topics such as:

try:
suite
Fundamental programming concepts, including statements, expressions,
except expression-target:
interpreters, and compilers
suite
except:
Python basics, including operators, string formatting, namespaces, classes, errors,
suite
and exceptions
else:
Object-oriented programming concepts
suite
input/output
The percentage isFile1.0
The percentage is 1.0
Python'slast):
intrinsic functions
Traceback (innermost
File "<stdin>",Formatting,
line 1,
in ?
parsing, and manipulating strings
File "C:\\.\divby0_2.py", line 19, in ?
File "C:\\.\divby0_2.py",
4, and
inworking
figurePercentage
Interfacing with theline
Java APIs
with Java Streams
AttributeError: __getitem__
Using Python and Java Swing to create GUIs
Using our denominator example (divby0_4.py), if we want to determine if any exceptions occurred, we can add
anelse clause to the end Working
of our try
statement
follows:
with
SQL andasJDBC(TM)

def figurePercentage(figures):
Python and Java applets
for tuple in figures:
Intry:
addition, the book contains instructions for downloading and installing the Python
language and
the Java Development
Kit (JDK). Terminology, definitions, explanations,
numerator
= tuple[0]
and numerous
code samples make
this book a useful learning experience.
denominator
= tuple[1]
percent = numerator/denominator
Whether you
are a sophisticated
computer
percent
= percent
* user
100new to programming or a serious
applicationprint
developer,
Python
Programming
withis
the Java(TM)
Class Libraries
will
("The percentage
" + `percent`
+ "%")
give
you
insight
into
the
power
of
Python
and
the
know-how
to
put
it
to
work.
except ZeroDivisionError:
print ("divide by 0 percentage error")

777
except:

print ("percentage error")

else:Programming with the Java Class Libraries: A Tutorial for Building


Python
print Applications
("No exceptions
occurred")
Web and Enterprise
with Jython
By Richard Hightower
If no exceptions occurred, the figurePercentage() function prints out "No exceptions
occurred" during each
iteration in which that statement remains true.
Publisher: Addison Wesley
Pub Date: June 28, 2002
ISBN: 0-201-61616-5
TheTable
raise
Statement
of

Contents

Pages: 640

Araise statement forces an exception to be raised. One form is


Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming
language for more than a decade, and is used by
raise exception-expression,
description-expression
novices and professionals alike. In particular, its close relationship to Java(TM) makes
In our denominator example,
it raises a specific
exception.
the two languages,
when used
in combination, ideal for Web and distributed enterprise
application development.

>>> raise ZeroDivisionError, "Sequence has a Zero value in the denominator"


Traceback (innermost
last):
This tutorial begins
with coverage of some of the basics of Python programming. Using
File "<stdin>",
1, in
?
plenty of line
skill-building
exercises
and interactive programming sessions, this book will
ZeroDivisionError:
Sequence
has a
Zeroan understanding
value in the
denominator
help those new
to programming
develop
of concepts
and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
Theexception-expression
must be
type that
String
be an instance
object.
The
capabilities and shows
theofways
Pythonorinterfaces
with Java
APIs
for professional
description-expression
is
optional.
If
you
use
raise
with
no
exception-expression
, it
application development.
reraises the last exception.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
You can easily define
your
own exception
using awith
string
variable.
and
Enterprise
Applications
Jython
covers important topics such as:

>>> badListForm = 'badListForm'


>>> try:
Fundamental programming concepts, including statements, expressions,
...
raise badListForm,
"The list had a malformed tuple"
interpreters, and compilers
... except badListForm, msg:
Python basics, including
operators,
formatting, namespaces,
errors,
...
print ("Exception
occurred
:" string
+ badListForm
+ " "classes,
+ msg)
and exceptions
...
Exception occurred :badListForm The list had a malformed tuple
Object-oriented
concepts
>>> raise badListForm,
"Hi programming
Mom"
>>> badListForm = 'badListForm'
File input/output
>>> try:
...
raise badListForm,
"The list had a malformed tuple"
Python's intrinsic functions
... except badListForm, msg:
...
print ("Exception
occurred
:" + strings
badListForm + " " + msg)
Formatting, parsing,
and manipulating
...
Exception occurred
:badListForm
The and
list
had
a Java
malformed
tuple
Interfacing
with the Java APIs
working
with
Streams
>>> raise badListForm, "Hi Mom"
Using Python and Java Swing to create GUIs
Working with SQL and JDBC(TM)

Strings:
Bad Style for Exceptions
Python and Java applets
The use of strings
to raisethe
exceptions
has fallen
out of favor
and will likely
be installing
phased out
the
In addition,
book contains
instructions
for downloading
and
theofPython
language. Thelanguage
more "Pythonically"
methodKit
is to(JDK).
use a class
instance,definitions,
which we'llexplanations,
cover a
and the Javacorrect
Development
Terminology,
little later. I used
string example
here because
strings
easy tolearning
define and
thus make it easy to
and the
numerous
code samples
make this
bookare
a useful
experience.
illustrate exceptions.
Whether you are a sophisticated computer user new to programming or a serious
application
developer, Python Programming
with the
Java(TM)
will
Here's how we can modify
our figurePercentage()
example
to handle
and Class
reraiseLibraries
(throw) an
exception
give
you
insight
into
the
power
of
Python
and
the
know-how
to
put
it
to
work.
we've already defined:

badListForm = 'badListForm'

777

def figurePercentage(figures):

for tuple
figures:
Pythonin
Programming
with the Java Class Libraries: A Tutorial for Building
try:
Web
and Enterprise Applications with Jython
numerator = tuple[0]
By Richard Hightower
denominator = tuple[1]
= numerator/denominator
Publisher:percent
Addison Wesley
percent
= percent * 100
Pub Date: June 28, 2002
print
("The
percentage is " + `percent` + "%")
ISBN: 0-201-61616-5
Table of
except
ZeroDivisionError:
Pages: 640
Contents
print ("divide by 0 percentage error")
raise
Characterized
by ease of use, richness of expression, and concise syntax, Python has
except
AttributeError:
remained a premier
programming language for more than a decade, and is used by
raise badListForm,
"An
item
in the
list is
not a sequence
novices and professionals
alike. In particular,
its close
relationship
to Java(TM)
makes
IndexError:
theexcept
two languages,
when used in combination, ideal for Web and distributed enterprise
raise badListForm, "A sequence in the list does" \
application development.
" not have two items"
except:
This
tutorial begins with coverage of some of the basics of Python programming. Using
print ("percentage
error")
plenty of skill-building
exercises and interactive
programming sessions, this book will
else:
help
those new to programming develop an understanding of concepts and practical
#print
("No
exceptions
occurred")
techniques. For
experienced
programmers,
the book
demonstrates Python's breadth of
pass
capabilities and
shows the ways that Python interfaces with Java APIs for professional

application development.
First, let's examine the ZeroDivisionError exception handler
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
except ZeroDivisionError:
and Enterprise Applications with Jython covers important topics such as:

print ("divide by 0 percentage error")


raise

Fundamental programming concepts, including statements, expressions,


which, as we see, prints outinterpreters,
an error message
and then uses the raise statement with no expressions.
and compilers
(Remember, raise with no expressions reraises the active exception.) The following code snippet passes a list
Python
basics,
including operators, string formatting, namespaces, classes, errors,
containing a tuple with a zero
for the
denominator:
and exceptions

try:

programming concepts
print("TheObject-oriented
nice list")
figures = [(10.0,20.0), (100.0, 200.0), (300.0, 400.0), (1.0, 0.0), (1
File input/output
figurePercentage(figures)
except ZeroDivisionError, msg:
Python's intrinsic+functions
print("Exception:"
`ZeroDivisionError` + ": " + msg)
Formatting, parsing,
and
manipulating
strings
As soon as figurePercentage()
hits the
zero
denominator
tuple ( (1,0,0,0)), it catches the
exception, prints a message,
and
then
reraises
the
exception,
which
in the
above
will be caught by the
Interfacing with the Java APIs and working
with
Javacode
Streams
exception handler at the top of the call stack. Here's the output:
Using Python and Java Swing to create GUIs

The percentage is 50.0%


The percentage isWorking
50.0%
with SQL and JDBC(TM)
The percentage is 75.0%
divide by 0 percentage
Python anderror
Java applets
Exception:'ZeroDivisionError': float division

In addition, the book contains instructions for downloading and installing the Python
In the following example,
we and
define
own
exception, badListForm
, and raise
it when we
get an
language
theour
Java
Development
Kit (JDK). Terminology,
definitions,
explanations,
AttributeError
an IndexError
. Notice
raise
statement
used to raise
andornumerous
code samples
makethat
this the
book
a useful
learningisexperience.
badListForm with two different messages.
Whether you are a sophisticated computer user new to programming or a serious
badListForm =application
'badListForm'
developer, Python Programming with the Java(TM) Class Libraries will
... give you insight into the power of Python and the know-how to put it to work.

...
except AttributeError:
raise badListForm, "An item in the list is not a sequence"
except IndexError:

777

raise
badListForm,
sequence
in the
listfordoes"
Python
Programming
with the "A
Java
Class Libraries:
A Tutorial
Building\
" not have
items"
Web and Enterprise Applications
with two
Jython
By Richard Hightower
Therefore, if we execute the code snippet
Publisher: Addison Wesley

try:

Pub Date: June 28, 2002


print("-")
ISBN: 0-201-61616-5
list with a non sequence")
Table print("The
of

Pages:
640
nasty_list = [(1.0,
1.0), (2.0, 2.0), 2, (3.0, 3.0)]
Contents
figurePercentage(nasty_list)
Characterized
by ease of use, richness of expression, and concise syntax, Python has
except badListForm,
msg:
remained
a
premier
programming
language for more than
is used by
print ("Exception:"
+ `badListForm`
+ a"decade,
: " and
+ msg)
novices
and
professionals
alike.
In
particular,
its
close
relationship
to
Java(TM)
makes
try:
the
two
languages,
when
used
in
combination,
ideal
for
Web
and
distributed
enterprise
print("-")
application
development.
print("The
list
with a sequence that contains less items than 2")
nasty_list = [(1.0, 1.0), (2.0, 2.0), [3], (4.0, 4.0)]
This tutorial begins with coverage of some of the basics of Python programming. Using
figurePercentage(nasty_list)
plenty of skill-building exercises and interactive programming sessions, this book will
except badListForm, msg:
help those new to programming develop an understanding of concepts and practical
print ("Exception:" + `badListForm` + " : " + msg)

techniques. For experienced programmers, the book demonstrates Python's breadth of


and shows the ways that Python interfaces with Java APIs for professional
we get the followingcapabilities
output:
application development.

Programming
with the Java(TM) Class Libraries: A Tutorial for Building Web
The list withPython
a non
sequence
and
Enterprise
Applications
with Jython covers important topics such as:
The percentage is 100.0%
The percentage is 100.0%
Exception:'badListForm'
An item concepts,
in theincluding
list statements,
is not expressions,
a sequence
Fundamental:programming
interpreters, and compilers
The list with a sequence that contains less items than 2
The percentage isPython
100.0%
basics, including operators, string formatting, namespaces, classes, errors,
The percentage isand100.0%
exceptions
Exception:'badListForm' : A sequence in the list does not have two items
Object-oriented programming concepts
File input/output

Equality Is Not Enough

Python's intrinsic functions

Having the same value


string is not
enough.
string exception
Formatting,
parsing,
andThe
manipulating
strings in the except clause must be
exactly the same as the object that was raised, which in Pythonese means
Interfacing with the Java APIs and working with Java Streams

str1 == str2 being true is not enough


Using Python and Java Swing to create GUIs
instead of

Working with SQL and JDBC(TM)

str1 is str2 has to be true.


Python and Java applets

The finally Clause


In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
The second of the two
of try
cleans
up anmake
exception.
It includes
finally
clause, and looks like this:
andforms
numerous
code
samples
this book
a usefulalearning
experience.

try:

Whether you are a sophisticated computer user new to programming or a serious

suite application developer, Python Programming with the Java(TM) Class Libraries will
finally:
give you insight into the power of Python and the know-how to put it to work.
suite

777

You can't use a finally clause and an except clause in the same try statement.

Here's a simple try...finally


example:
Python Programming
with the Java

Class Libraries: A Tutorial for Building


Web and Enterprise Applications with Jython
By Richard Hightower

>>> try:
...
raise "hello", "Hello Error"
...
print "Hello"
Publisher: Addison Wesley
... finally: Pub Date: June 28, 2002
...
print "Finally"
ISBN: 0-201-61616-5
... Table of
Pages: 640
Contents
Finally
Traceback (innermost last):
Characterized by ease of use, richness of expression, and concise syntax, Python has
File "<stdin>", line 2, in ?
remained a premier programming language for more than a decade, and is used by
hello: Hello Error

novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two
languages,
whenthat
used
combination,
idealwill
forbe
Web
and distributed
enterprise
Thetry...finally
clause
guarantees
theinfinally
clause
executed
whether or
not an
application
development.
exception occurs. You want cleanup code in a finally clauseit's like closing a database connection or a
file. We'll use finally a lot when we deal with files in Chapter 8.
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
those new to programming
develop an understanding of concepts and practical
Classes andhelp
Instances
as Exceptions
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities
and shows
ways object,
that Python
interfaces
with JavaThe
APIs
professional
Earlier we defined our
own exception
usingthe
a string
making
it user defined.
newforPython
way of
development.
defining exceptions application
is with classes
and class instances, which means that the raise statement can take the
following form:
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
Enterprise Applications with Jython covers important topics such as:
raise class, and
class_instance

raise class_instance
Fundamental programming concepts, including statements, expressions,
andofcompilers
In the except clause, youinterpreters,
list the name
the class. If the exception instance raised is an instance of that class
(a direct instance or an instance of a subclass), except will catch it. The exception class you define should be
Python basics, including operators, string formatting, namespaces, classes, errors,
derived from the Exceptionand
class,
which is defined in the exception module (exception.py). As of now, this isn't a
exceptions
requirement, but it likely will be in the future. If you use an instance of Exception in conjunction with the
str() function, it will return
all of the arguments
passed
to its constructor.
Object-oriented
programming
concepts
I know these concepts are hard
to visualize, so let's do a few quick examples to make them easier to grasp.
File input/output

Type Exception

Python's intrinsic functions

Formatting, parsing, and manipulating strings


First we raise an error of type Exception as follows:
Interfacing with the Java APIs and working with Java Streams

>>> try:
...
error = Using
Exception("Not
working",
"Something Broke", "Better call for
Python and Java Swing
to create GUIs
...
raise error
... except Exception:
Working with SQL and JDBC(TM)
...
print "Got an error"
Python and Java applets
...
Got an error
In addition, the book contains instructions for downloading and installing the Python
>>>
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous
samples make
this book a handler,
useful learning
experience.
We catch the raised exception
withcode
our except
Exception:
which is
useful but doesn't do
anything with the arguments we passed as our exceptions instance.
Whether you are a sophisticated computer user new to programming or a serious
application
developer,
Python
Programming
with the
Java(TM)
Class Libraries
will in
The next listing (chap7_1)
shows
how to use
the arguments
we passed
to the
Exception
constructor
insight into
the going
powertoofmake
Python
and gradually
the know-how
put it toso
work.
conjunction with thegive
stryou
statement.
(We're
things
more to
complex,
be sure to follow
along.)

try:

777

error = Exception("Not working", "Something Broke", "call for help")

raise error
Python Programming with the Java Class Libraries: A Tutorial for Building
except Exception,
Web andinstance:
Enterprise Applications with Jython
print "Got
anHightower
error " + str( instance)
By Richard
print instance.__class__.__name__
Publisher: Addison Wesley

As you can see, the second


argument passed to the exception handler is the instance we raised. When you use the
Pub Date: June 28, 2002
str statement with the instance of the Exception class, you get the argument passed to the constructor
ISBN: 0-201-61616-5
Tabletoofa string. The output from the above code is
converted

Contents

Pages: 640

Got an error ('Not working', 'Something Broke', 'call for help')


Characterized by ease of use, richness of expression, and concise syntax, Python has
Exception

remained a premier programming language for more than a decade, and is used by
novices
and
alike. toInthe
particular,
its clause
close relationship
Java(TM)
Just so we leave no doubt
that
theprofessionals
second argument
except
is in fact thetoinstance
we makes
threw (I
the
two
languages,
when
used
in
combination,
ideal
for
Web
and
distributed
enterprise .
meant to say "raised"more on this later), we print out the name of the instance class, that is, Exception
application development.

User-Defined Class-Based
This tutorial begins Exceptions
with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
To round out our examples
of class-based
exceptions,develop
we'll create
our own (thatofis,concepts
user-defined).
Of course, we
help those
new to programming
an understanding
and practical
did this before usingtechniques.
the old wayFor
withexperienced
string objects,
but now we'll
it using
classes. Here
is a breadth
listing of
programmers,
the do
book
demonstrates
Python's
(chap7_2) that defines
three user-defined
capabilities
and showsexceptions.
the ways that Python interfaces with Java APIs for professional
application development.

Listing chap7_2
class CarException(Exception):
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
pass and Enterprise Applications with Jython covers important topics such as:
class BrakeFailed(CarException):
pass
Fundamental programming concepts, including statements, expressions,
class EngineFailed(CarException):
interpreters, and compilers
pass
if __name__ == "__main__":
Python basics, including operators, string formatting, namespaces, classes, errors,
main()
and exceptions
def main():
try:
Object-oriented programming concepts
error = BrakeFailed("Not working", "Something Broke",
"Better call for help", "Get an Airbag")
File input/output
raise error
except BrakeFailed,
instance:
Python's intrinsic functions
print "Got a BrakeFailed exception " + str(instance) \
+ "parsing,
" + and
instance.__class__.__name__
Formatting,
manipulating strings
try:
Interfacing
with the
APIs and working with Java Not
Streams
error
= Java
BrakeFailed("Brakes
working", "Something Bro
raise error
Using Python and Java
Swing to create GUIs
except CarException,
instance:
print "Got a Car Exception " + str(instance) + " " \
Working with SQL and JDBC(TM)
+ instance.__class__.__name__
except Exception,
instance:
Python and Java
applets
print "Got an exception " + str(instance) + " " \
instance.__class__.__name__
In addition, the+book
contains instructions for downloading and installing the Python
try: language and the Java Development Kit (JDK). Terminology, definitions, explanations,
= BrakeFailed("Not
working",
"Something Broke", "B
and numerouserror
code samples
make this book a useful learning
experience.
raise error
you are a sophisticated
computer user new to programming or a serious
exceptWhether
Exception,
instance:
application developer,
with the Java(TM)
Class Libraries will+ " " \
print Python
"GotProgramming
an exception
" + str(instance)
give you insight
the power of Python and the know-how to put it to work.
+ into
instance.__class__.__name__
Here's the output:

777

Got a BrakeFailed exception ('Not working', 'Something Broke', 'Better call f

Got an exception
working',
Broke',
'Better
call for help', '
Python('Not
Programming
with the 'Something
Java Class Libraries:
A Tutorial
for Building
BrakeFailed Web and Enterprise Applications with Jython
Got a Car Exception
('Brakes Not working', 'Something Broke', 'Better call fo
By Richard Hightower
Publisher: Addison Wesley
Exception Hierarchy
Pub Date: June 28, 2002

ISBN:
UsingTable
the class
approach, you
can 0-201-61616-5
build a hierarchy of exceptions. This allows programmers who use the
of

Pages:
640
methods
of one of your classes to decide the level of detail or granularity they care about. For example, you can
Contents
define 30 CarException classes that can be thrown when the Car class startsthat is, when someone calls
Characterized
by ease
richness
of expression,
and concise
syntax, Python
hasonly if
the class's __start__
method. One
userofofuse,
your
Car class
may care about
all 30. Another
may care
remained
a
premier
programming
language
for
more
than
a
decade,
and
is
used
by
anyCarException is thrown and therefore write an except clause only to catch any exception derived
novices and professionals alike. In particular, its close relationship to Java(TM) makes
from it.
the two languages, when used in combination, ideal for Web and distributed enterprise
The first try block application
in the maindevelopment.
function of the chap7_2 module raises an instance of BrakeFailed. Here
we demonstrate an except clause that catches a BrakeFailed class. The second parameter should be the
instance we raised. This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
try:
help those new to programming develop an understanding of concepts and practical
error techniques.
= BrakeFailed("Not
working",
"Something
Broke",
"Better
call for
For experienced programmers,
the book
demonstrates Python's
breadth
of
raise capabilities
error and shows the ways that Python interfaces with Java APIs for professional
except BrakeFailed,
instance:
application development.

print "Got a BrakeFailed exception " + str(instance) + " " \


Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
+ instance.__class__.__name__
and Enterprise Applications with Jython covers important topics such as:
To take our demonstration further, we show that not only can we catch a BrakeFailed instance with an
except clause that specifies a BrakeFailed class, but we can also catch the BrakeFailed instance
Fundamental programming
with any base class of the BrakeFailed
base class.concepts, including statements, expressions,
interpreters, and compilers

try:

Python basics, including operators,


formatting, namespaces,
classes,
errors,
error = BrakeFailed("Brakes
Notstring
working",
"Something
Broke",
"Better c
and
exceptions
raise error
except CarException, instance:
Object-oriented programming concepts
print "Got a Car Exception " + str(instance) + " " \
+ instance.__class__.__name__
File input/output
In the above code, we catchPython's
the BrakeFailed
instance with an except block that specifies a
intrinsic functions
CarException. We can do this because CarException is a base class of BrakeFailed. We can
also catch a BrakeFailed
class with
any base
Formatting,
parsing,
andclass.
manipulating strings

try:

Interfacing with the Java APIs and working with Java Streams

error = BrakeFailed("Not working", "Something Broke", "Better call for


raise error
Using Python and Java Swing to create GUIs
with SQL and JDBC(TM)
except Exception,Working
instance:
print "Got an exception " + str(instance) + " " \
Python and Java applets
+ instance.__class__.__name__
In addition, the book
contains
forhandler
downloading
and installing
Python
Here we catch the BrakeFailed
instance
withinstructions
the exception
(the except
clause)the
using
the
language
and
the
Java
Development
Kit
(JDK).
Terminology,
definitions,
explanations,
Exception class. With the above approach we can create hierarchies of exceptions that can all be caught by
andspecify
numerous
code samples
this book a useful learning experience.
except clauses that
the exceptions'
basemake
classes.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

Don't Give Up

Publisher: Addison
Wesley fire up the interactive interpreter and import the
If you still don't understand
these concepts,
BrakeFailed
class
from
module
chap7_2, and try raising and catching the error inside a try
Pub
Date:
June
28, 2002
block.
ISBN: 0-201-61616-5

Table of
Contents

Pages: 640

Once again, the only way to learn programming is to program. I guarantee that the people having
the hardest time
understanding
this chapter
are probably
the ones who
following
along with
Characterized
by ease
of use, richness
of expression,
and aren't
concise
syntax, Python
has
the examples.remained
Remember,
if a picture
is worth alanguage
thousandfor
words,
working
modeland
is worth
a premier
programming
moreathan
a decade,
is useda by
thousand pictures.
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application
development.
Most to Least Specific
Order

This tutorial begins with coverage of some of the basics of Python programming. Using
What happens if you have two except clauses that both catch base classes of the instance you're throwing
plenty of skill-building exercises and interactive programming sessions, this book will
(raising)? Does the most specific class prevail? By most specific, I mean the class that's closest in the class
help those new to programming develop an understanding of concepts and practical
hierarchy to the class of the instance being raised. Look at the listing for chap7_2, which shows the catch()
techniques. For experienced programmers, the book demonstrates Python's breadth of
method.
capabilities and shows the ways that Python interfaces with Java APIs for professional
def catch(): application development.

print "the most specific to the least specific"


Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
try:
and Enterprise Applications with Jython covers important topics such as:
error = BrakeFailed()
raise error
except BrakeFailed,
instance:
Fundamental programming
concepts, including statements, expressions,
print
"I
got
it1"
interpreters, and compilers
except CarException, instance:
Python
basics, including
operators,
string
formatting,
print
"Excuse
me, but
I've
got
it2"namespaces, classes, errors,
and exceptionsinstance:
except Exception,
print "No I beg your pardon, I've got it3"
Object-oriented
programming
concepts
print "Least
specific
to most
specific"
try:
File input/output
error
= BrakeFailed()
raise
error
Python's intrinsic functions
except Exception, instance:
print
"Exception"
Formatting,
parsing, and manipulating strings
except CarException, instance:
print
"CarException"
Interfacing
with the Java APIs and working with Java Streams
except BrakeFailed, instance:
Using
Python and Java Swing to create GUIs
print
"BrakeFailed"
Working
with SQL and
In the following excerpt from
chap7_2.catch(),
we JDBC(TM)
see that the BrakeFailed exception is being raised and
that there are three except clauses that can potentially catch it.
Python and Java applets

try:
the book contains instructions for downloading and installing the Python
error In=addition,
BrakeFailed()
language
and
the Java Development Kit (JDK). Terminology, definitions, explanations,
raise error
and
numerous
code samples make this book a useful learning experience.
except BrakeFailed, instance:
print "I got it1"
Whether you are a sophisticated computer user new to programming or a serious
except CarException, instance:
application developer, Python Programming with the Java(TM) Class Libraries will
print "Excuse me, but I've got it2"
give you insight into the power of Python and the know-how to put it to work.
except Exception, instance:
print "No I beg your pardon, I've got it3"

777

The first except can catch BrakeFailed simply because it declares BrakeFailed in its clause. The
nextexcept also seems like a candidate because it declares a CarException in its clause and

CarException is
a baseProgramming
class of BrakeFailed
. The third
seems
to be a for
candidate
as well
Python
with the Java
Classexcept
Libraries:
A Tutorial
Building
becauseException
is also
base class of
BrakeFailed
. (Exception is a direct base class of
Web
and aEnterprise
Applications
with Jython
CarException,By
and
CarException
is a base class of BrakeFailed; thus, Exception is a base
Richard
Hightower
class of BrakeFailed, and an instance of BrakeFailed is also an instance of Exception.)
Publisher: Addison Wesley

If we run the above code


segment, we get
Pub Date: June 28, 2002
ISBN: 0-201-61616-5

I got
it1
Table
of

Pages: 640

Contents

So in this case the most specific except caught the exceptionthat is, the first one, which has
bybeing
ease of
richness
expression,
concisecode
syntax,
BrakeFailed inCharacterized
its clause. This
theuse,
case,
what doofyou
think theand
following
willPython
do? Is has
it always
remained
a
premier
programming
language
for
more
than
a
decade,
and
is
used
by
the case that the most specific except clause will catch the exception?
novices and professionals alike. In particular, its close relationship to Java(TM) makes
try:
the two languages, when used in combination, ideal for Web and distributed enterprise
error application
= BrakeFailed()
development.

raise error
This tutorial
begins with coverage of some of the basics of Python programming. Using
except Exception,
instance:
plenty
of
skill-building
exercises and interactive programming sessions, this book will
print "Exception"
help
those
new
to
programming
except CarException, instance: develop an understanding of concepts and practical
For experienced programmers, the book demonstrates Python's breadth of
print techniques.
"CarException"
capabilities
shows the ways that Python interfaces with Java APIs for professional
except BrakeFailed, and
instance:
development.
print application
"BrakeFailed"
Python
Programming
Java(TM)
Classclauses
Libraries:
Tutorial
for Building
Web we
Unlike the last example,
here
we organizedwith
the the
order
of except
fromAleast
to most
specific. When
and
Enterprise
Applications
with
Jython
covers
important
topics
such
as:
run this code, we get the following output:

Exception

Fundamental programming concepts, including statements, expressions,


interpreters, and compilers

Java versus
Python versus Delphi versus Visual
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
Basic Exception Handling
Object-oriented programming concepts
Java's handling of exceptions is very similar to Python's. The following table shows the equivalent
exception statementsFile
in the
two languages as well as in Delphi and Visual Basic.
input/output
Python

Java
Delphi (Object
Python's intrinsic
functionsPascal) Visual Basic

try
try
try
on error goto label
Formatting,
parsing, and manipulatinglabel
strings
except catch
except
raise throw raise
raise
Interfacing with the Java APIs and working with Java Streams
finally finally finally
on error resume next
Using Python and Java Swing to create GUIs
Exception handling in Java and Python isn't completely the same. One key difference is that Java
allows you to declare
the typewith
of exception
a method will throw (that is, "raise" in Python).
Working
SQL andthat
JDBC(TM)
The method code must catch that exception or its base class.
Python and Java applets
Another key difference is that it's a syntax error in Java to list catch statements (except
In addition,
the book
contains
instructions
downloading
and
installing
Python
clauses in Python)
as anything
but most
to least
specific.for
This
feature won't
allow
you tothe
write
code
and In
themy
Java
Development
Kit (JDK).
Terminology,
explanations,
that will neverlanguage
be reached.
opinion,
Python should
do something
like definitions,
this or, better
yet,
numerous
code
samplestomake
this specific
book a useful
learning
experience.
should alwaysand
send
the raised
exception
the most
handler
( except
clause).
Whether
yousimilar
are a sophisticated
new
programming
a serious
Python and Delphi
share
keywords, butcomputer
Python's user
syntax
fortohandling
errors or
seems
a little
application
developer,
Python Programming
with the
Class Libraries
closer to Java's
than to Delphi's.
Regardless,
exception handling
in Java(TM)
the three languages
is close.will
give you
insight
the power
of Python and the know-how to put it to work.
Visual Basic does
its own
typeinto
of error
handling.

777

Thus, the first except that has a base class of the class of the instance we're raising catches that raised
instance. The last two in the example are never reached. This proves that the most specific except does not
always catch the exception, and it means that we have to be careful in how we organize our except clauses to

make sure that they're


in mostProgramming
to least specificwith
order.
Python
the Java

Garden

Class Libraries: A Tutorial for Building


Web and Enterprise Applications with Jython
By Richard
Hightower
Variety
Exceptions

Publisher:
Addison Wesley
The exceptions described
in the subsections
that follow are used as base classes.
Pub Date: June 28, 2002

Exception
Table of

Contents

ISBN: 0-201-61616-5
Pages: 640

Exception is the root class for all exceptionsall built-in exceptions are derived from it, and all user-

Characterized
by ease
expression,session
and concise
defined exceptions should
be derived
fromof
it. use,
The richness
followingofinteractive
showssyntax,
that Python has
remained
a
premier
programming
language
for
more
than
a
decade,
and is used by
ZeroDivisionError is derived from Exception.
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
>>> try:
application development.
...
1/0

... except Exception, instance:


This tutorial begins with coverage of some of the basics of Python programming. Using
...
print instance.__class__.__name__
plenty of skill-building exercises and interactive programming sessions, this book will
...
help those new to programming develop an understanding of concepts and practical
ZeroDivisionError
StandardError

techniques. For experienced programmers, the book demonstrates Python's breadth of


capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.

StandardErrorPython
, derived
from Exception
, is the baseClass
classLibraries:
for all built-in
exceptions.
The following
Programming
with the Java(TM)
A Tutorial
for Building
Web
interactive session shows
that
StandardError
is
a
base
class
of
ZeroDivisionError
.
and Enterprise Applications with Jython covers important topics such as:
>>> try:
...
1/0
Fundamental programming concepts, including statements, expressions,
... except StandardError,
interpreters, anderror:
compilers
...
print error.__class__.__name__
...
Python basics, including operators, string formatting, namespaces, classes, errors,
ZeroDivisionErrorand exceptions
The code uses the StandardError
class
in the except
clause, which will catch all exceptions that are
Object-oriented
programming
concepts
either instances of StandardError or instances of its subclasses. (Remember, all instances of subclasses of
File input/output
StandardError are considered
instances of StandardError.)

Python's
intrinsic functions
As I said before, all user-defined
exceptions
should be subclasses of the Exception class, but don't subclass
your exception from StandardError, which is reserved for the built-in variety. It's easy to tell the
Formatting,
parsing, and
strings
difference between a system
(built-in) exception
andmanipulating
an application
(or library) exception. It's built in if it's an
instance of a StandardError subclass.
Interfacing with the Java APIs and working with Java Streams
ArithmeticError

Using Python and Java Swing to create GUIs

and JDBC(TM)
ArithmeticError isWorking
the base with
class SQL
for built-in
exceptions representing arithmetic errors, such as
OverflowError,ZeroDivisionError, and FloatingPointError.
Python and Java applets

>>> try:
In addition, the book contains instructions for downloading and installing the Python
...
1/0
language and the Java Development
... except ArithmeticError,
aerror:Kit (JDK). Terminology, definitions, explanations,
and
numerous
code
samples
make this book a useful learning experience.
...
print aerror
...
print aerror.__class__.__name__
Whetheror
youmodulo
are a sophisticated computer user new to programming or a serious
integer division
application
developer,
Python Programming with the Java(TM) Class Libraries will
ZeroDivisionError
give you insight into the power of Python and the know-how to put it to work.

LookupError

777

LookupError is a base class for the exceptions associated with items not in a collection object (mapping or

sequence)for example,
IndexError
and
KeyError
following
example
showsfor
how
to catch a
Python
Programming
with
the Java. The
Class
Libraries:
A Tutorial
Building
LookupError: Web and Enterprise Applications with Jython
By Richard Hightower

>>> dictionary = {"Hello":"Hi", "Goodbye":"Bye", "See ya Later":"Later"}


>>> print dictionary["Hello"]
Publisher: Addison Wesley
Hi
Pub Date: June 28, 2002
>>> try:
ISBN: 0-201-61616-5
... Table
print
dictionary["Ciao"]
of
Pages: 640
... Contents
except LookupError, error:
...
print error.__class__.__name__
Characterized by ease of use, richness of expression, and concise syntax, Python has
...
remained a premier programming language for more than a decade, and is used by
KeyError
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two
when
used in combination,
ideal for
Web and distributed enterprise
We can see that KeyError
is languages,
a subclass of
LookupError
, from which
it derives.
application development.
AttributeError

This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
AttributeError
used new
in conjunction
with classes
andaninstances.
It signifies
an attribute
reference or a
helpisthose
to programming
develop
understanding
of concepts
and practical
failed assignment. techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
>>> class clazz:
application development.

...
a = 1
...
b = "hi"
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
...
c = None
and Enterprise Applications with Jython covers important topics such as:
...
>>> clazz.b
Fundamental programming concepts, including statements, expressions,
'hi'
interpreters, and compilers
>>> try:
...
clazz.a = clazz.e
Python basics, including
operators, string formatting, namespaces, classes, errors,
... except AttributeError,
error:
and
exceptions
...
print "Class does not support attribute e"
...
Object-oriented
programming
Class does not support
attribute
e concepts
File input/output

EOFError

Python's intrinsic functions

EOFError signifies that a built-in function has hit the end of the filepossibly unexpectedly. We'll leave this
parsing, and manipulating strings
example to Chapters 8 andFormatting,
9.
FloatingPointError

Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs

FloatingPointError signifies the failure of a floating-point operation.


Working with SQL and JDBC(TM)
IOError

Python and Java applets


IOError signifies failure of an I/O operation. We'll discuss this more in Chapter 9.
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
IndexError
and numerous code samples make this book a useful learning experience.

IndexError signifies
thatyou
a subscript
is out of range.
The following
shows how
might get such
Whether
are a sophisticated
computer
user new example
to programming
or a you
serious
an exception:

application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

>>> seq = (1,2,3,4,5)


>>> seq[1]
2
>>> seq[5]

777

Traceback (innermost
last): with the Java Class Libraries: A Tutorial for Building
Python Programming
File "<stdin>",
1, Applications
in ?
Web andline
Enterprise
with Jython
IndexError: tuple
out of range
By Richardindex
Hightower
KeyError

Publisher: Addison Wesley


Pub Date: June 28, 2002

KeyError signifies a keyISBN:


not found
in a dictionary, which the following example demonstrates:
0-201-61616-5

Table of

Pages: 640

>>> Contents
dictionary = {"Hello":"Hi", "Goodbye":"Bye", "See ya Later":"Later"}
>>> print dictionary["Hello"]
Characterized by ease of use, richness of expression, and concise syntax, Python has
Hi
remained a premier programming language for more than a decade, and is used by
>>> try:
novices and professionals alike. In particular, its close relationship to Java(TM) makes
...
print dictionary["Ciao"]
the two languages, when used in combination, ideal for Web and distributed enterprise
... except KeyError,
error:
application development.
...
print "Ciao not in dictionary"
...
This tutorial begins with coverage of some of the basics of Python programming. Using
Ciao not in dictionary
plenty of skill-building exercises and interactive programming sessions, this book will
>>>
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
Does this example look
familiar?and
Asshows
an exercise,
compare
it to the
one for LookupError
capabilities
the ways
that Python
interfaces
with Java APIs for. professional
application development.
NameError

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and that
Enterprise
important topics such as:
NameError signifies
a nameApplications
isn't found inwith
the Jython
currentcovers
namespace.

>>> name1 = None


>>> name2 = None Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
>>> name1
>>> name2
Python basics, including operators, string formatting, namespaces, classes, errors,
>>> name3
and exceptions
Traceback (innermost
last):
File "<stdin>",Object-oriented
line 1, in
?
programming concepts
NameError: name3
File input/output
Here two variables, name1 and name2, are defined. After the interactive session accesses their values, it tries
to access a variable that it didn't
define.
Thus,functions
an exception is uncaught and displayed in the interactive
Python's
intrinsic
interpreter.
Formatting, parsing, and manipulating strings
To catch the exception, we do this:
Interfacing with the Java APIs and working with Java Streams

>>> try:
...
print name3Using Python and Java Swing to create GUIs
... except NameError, error:
Working
with SQL
and JDBC(TM)
...
print "name3
is not
present"
...
Python and Java applets
name3 is not present
>>>
OverflowError

In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.

OverflowErrorWhether
signifiesyou
thatare
a number
is too big
to fit in user
a number
a sophisticated
computer
new tovariable.
programming or a serious
TypeError

application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

TypeError signifies that the code is trying to use a built-in object with a function or operation that doesn't

777

support it. In this example, we try to multiply a list by another list, which can't be done. We'll try to get a
TypeError.

Python Programming with the Java Class Libraries: A Tutorial for Building
>>> list = [1,2,3]
Web and Enterprise Applications with Jython
>>> list2 = [1,2,3]
By Richard
Hightower
>>> list = list
* list2
Traceback (innermost last):
Publisher:line
Addison
Wesley
File "<console>",
1,
in ?
Pub Date:
June 28,sequence
2002
TypeError: can't
multiply
with non-int
ISBN: 0-201-61616-5

Table of
Do you
remember that a dictionary
key has to be immutable? If you use a mutable object as a key, what happens?

Pages: 640
Contents
Fire up the interactive interpreter, and try the following example:
Characterized by ease of use, richness of expression, and concise syntax, Python has
>>> dict = {}remained a premier programming language for more than a decade, and is used by
>>> list = [1,2,3]
novices and professionals alike. In particular, its close relationship to Java(TM) makes
>>> dict[list]="item"
the two languages, when used in combination, ideal for Web and distributed enterprise
Traceback (innermost
last):
application development.

File "<console>", line 1, in ?


TypeError: unhashable
type
This tutorial begins
with coverage of some of the basics of Python programming. Using

plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities
and shows
thatoperation
Python interfaces
withInJava
for professional
ValueError signifies
the wrong
type forthe
theways
current
or function.
thisAPIs
example,
the string module
application
development.
uses it to indicate that
a string can't
be evaluated to a number when the atoi (ASCII-to-Integer) function is
called (see Chapter 10).
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
>>> import string
ValueError

>>> string.atoi("123")
123
Fundamental programming concepts, including statements, expressions,
>>> string.atoi("YOU")
interpreters,
and compilers
Traceback (innermost
last):
File "<interactive
input>", line 0, in ?
Python basics, including operators, string formatting, namespaces, classes, errors,
ValueError: invalid
literal
for atoi(): YOU
and exceptions
First the code imports the string module and then invokes the module's atoi function to convert the string
Object-oriented programming concepts
"123" to an integer. Next it uses atoi to convert the string "YOU" to an integer, which raises a
ValueError exceptionFile
because
that string has no integer equivalent.
input/output

ValueError is used inPython's


all kindsintrinsic
of modules.
It's a nice way of saying that the value is out of the range a
functions
particular function was expecting.
Formatting, parsing, and manipulating strings
ZeroDivisionError
Interfacing with the Java APIs and working with Java Streams
We used ZeroDivisionError a lot in the examples earlier in the chapter. Remember that it occurs when
Using Python and Java Swing to create GUIs
you have a zero in the denominator.

Working with SQL and JDBC(TM)

>>> 1/0
Traceback (innermost
last):
Python and
Java applets
File "<stdin>", line 1, in ?
ZeroDivisionError:
division
modulo and installing the Python
In addition, theinteger
book contains
instructions or
for downloading

Getting the

language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous
this book a useful learning experience.
Most
Outcode
ofsamples
Yourmake
Exceptions

Whether you are a sophisticated computer user new to programming or a serious


Exception class instances
have the
attributesPython
filename
,lineno
,offset
, and text
. You can will
access
application
developer,
Programming
with
the Java(TM)
Class Libraries
these details to locategive
where
your
code
failed.
The
next
example
(chap7_3.py)
shows
how:
you insight into the power of Python and the know-how to put it to work.

class MyException(Exception):
pass
def raiseMyException():

777

raise Python
Exception()
Programming with the Java Class Libraries: A Tutorial for Building
def catchMyException():
Web and Enterprise Applications with Jython
try: ByRichard Hightower
raiseMyException()
except MyException,
err:
Publisher: Addison Wesley
print
"line
number
" +err.lineno
Pub Date: June 28, 2002
print
"file
name
"
+ err.filename
ISBN: 0-201-61616-5
Table of
print
"offset
"
+
err.offset

Pages: 640
Contents
print " text " + err.text
Characterized by ease of use, richness of expression, and concise syntax, Python has
Summary remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
Exception handling is easier than the traditional approach of always checking the return type from functions.
application development.
Exceptions can be class objects or string objects, although string object exceptions are no longer in favor. The
newer, more correct This
way tutorial
is to usebegins
class instances.
In fact,
as of Python
versionof1.5,
all ofprogramming.
the standard exceptions
with coverage
of some
of the basics
Python
Using
are class instances. plenty of skill-building exercises and interactive programming sessions, this book will
helpathose
to programming
understanding
concepts
andthat
practical
Thetry statement tries
blocknew
of code;
if that blockdevelop
raises ananexception,
try of
either
handles
exception or
techniques.
For
experienced
programmers,
the
book
demonstrates
Python's
breadth
of The
performs some type of cleanup. There are two forms of try. One has try,except, and else
clauses.
capabilities
and
shows
the
ways
that
Python
interfaces
with
Java
APIs
for
professional
except clause handles all exception classes derived from the class it mentions. The else clause is the default
application development.
handler for code that must be executed if no exceptions are raised.
Python
with thefinally
Java(TM) guarantees
Class Libraries:
A Tutorial
Building
Web
The other form of try
has Programming
a finally clause.
that some
form offor
cleanup
code
(like
and
Enterprise
Applications
with
Jython
covers
important
topics
such
as:
file closing) is performed. The raise statement allows programmers to raise an exception in their code.
Fundamental programming
concepts, including statements, expressions,
CONTENTS
interpreters, and compilers
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
Object-oriented programming concepts
File input/output
Python's intrinsic functions
Formatting, parsing, and manipulating strings
Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs
Working with SQL and JDBC(TM)
Python and Java applets
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
CONTENTS
Web and Enterprise Applications with Jython
By Richard Hightower

Chapter 8. Working
with Files
Publisher: Addison Wesley
Pub Date: June 28, 2002

Simple File Operations


ISBN: 0-201-61616-5
Table of
Common File Methods
Pages: 640
Contents
Putting It All Together: The Address Book Example
Characterized
by ease of use, richness of expression, and concise syntax, Python has
The Full address3.py
Code
remained a premier programming language for more than a decade, and is used by
Persisting Objects with pickle
novices and professionals alike. In particular, its close relationship to Java(TM) makes
pickle and the
Address
Bookwhen
Application
the two
languages,
used in combination, ideal for Web and distributed enterprise
Summary application development.

Terms in This Chapter


This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
Class instance
Java Virtual Machine
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities
interfaces with Java APIs for professional
Comm ent and shows the ways that PythonMethod
application development.
Data persistence
Mode
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and
important topics such as:
DataEnterprise
structure Applications with Jython covers
newline
Document string
Object instance
Fundamental programming concepts, including statements, expressions,
Dumpinterpreters, and compilers
pickle module

formatting, namespaces, classes, errors,


File Python basics, including operators, string
Scaffolding
and exceptions
File object
try except
Object-oriented programming concepts
File pointer
try finally
File input/output
for, if, and while statements
while loop
Python's intrinsic functions
for loop
Formatting, parsing, and manipulating strings
I've written programs that read and write data from files in Java, Delphi, Visual Basic, C++, and C. None have
withtothe
Java APIs
and working
withInJava
such a straightforward andInterfacing
easy approach
dealing
with files
as Python's.
thisStreams
chapter we'll be covering file
input and output, which is important for saving data. First we'll cover simple I/O; later we'll deal with persisting
Using Python and Java Swing to create GUIs
class instances.
Working
with
SQL and
JDBC(TM)
Writing a program that resides
only in
memory
is good
for illustration, but eventually you'll need to write that
program to a file. Do you remember our address book example in Chapter 4? What happened to the addresses
Python and Java applets
when the program ended? Gone, and that isn't good. We need a way to save addresses so that we can use them
again. Files fit the bill.
In addition, the book contains instructions for downloading and installing the Python

Simple File

language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and
numerous code samples make this book a useful learning experience.
Operations

Whether you are a sophisticated computer user new to programming or a serious


Before we begin our tour of files, we'll create a directory, c:\dat, where we'll put the data file we'll be working
application developer, Python Programming with the Java(TM) Class Libraries will
with throughout the chapter.
give you insight into the power of Python and the know-how to put it to work.
In Python, file I/O is built into the language, so working with files doesn't require an API or library. You just
make a call to the intrinsic (built-in) open() function, which returns a file object. The typical form of
open() is open(filename, mode).

777

Say, for example, that


you want
to open a filewith
in c:\dat
and write
"Hello
World"
to it.for
Here's
how to do
Python
Programming
the Java
Class
Libraries:
A Tutorial
Building
that. (Start up the interactive
interpreter
andApplications
follow along.)
Web and
Enterprise
with Jython
By Richard Hightower

>>>
>>>
>>>
>>>
>>>

file = open("c:\\dat\\hello.txt", "w")


file.write("Hello
World ")
Publisher: Addison Wesley
file.write("Hello
Mars ")
Pub Date: June 28, 2002
file.write("Hello Jupiter ")
ISBN: 0-201-61616-5
file.close()
Table
of
Pages: 640

Contents

Now, using your favorite editor, open up c:\dat\hello.txt. You should see this:
Characterized by ease of use, richness of expression, and concise syntax, Python has
remainedMars
a premier
programming
language for more than a decade, and is used by
Hello World Hello
Hello
Jupiter
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application
development.
Determining
the File Object Type

This tutorial begins with coverage of some of the basics of Python programming. Using
To see the type
of a of
fileskill-building
object, enter exercises and interactive programming sessions, this book will
plenty
those new to programming develop an understanding of concepts and practical
>>> file help
= open("\\dat\\test.dat","w")
techniques.
>>> type(file) For experienced programmers, the book demonstrates Python's breadth of

capabilities and shows the ways that Python interfaces with Java APIs for professional
Under Jythonapplication
and Jython development.
you get
Python Programming with the Java(TM)
Libraries: A Tutorial for Building Web
<jclass org.python.core.PyFile
at Class
2054104961>
and Enterprise Applications with Jython covers important topics such as:
Under Python (a.k.a CPython) you get
Fundamental programming concepts, including statements, expressions,
<type 'file'>
interpreters, and compilers

File Modes

Python basics, including operators, string formatting, namespaces, classes, errors,


and exceptions

The Python file object supports the following modes:


Object-oriented programming concepts
Write"w", " wb" File input/output
Read"r", " rb"

Python's intrinsic functions

Formatting,
Read and write"r+
", " r+b" parsing, and manipulating strings
Append"a", " ab"Interfacing with the Java APIs and working with Java Streams

Usingsignifies
Python and
Javawhich
Swingis to
create GUIs
The"b" appended to the mode
binary,
necessary
under Windows and Macintosh operating
systems to work with binary files. You don't need binary mode with Jython because its code executes in the
Working with SQL and JDBC(TM)
context of the Java Virtual Machine (JVM), which in this case is like a virtual operating system sitting atop the
base operating systems, making
alike. You don't need binary mode, either, if you're running
Pythonthem
andbehave
Java applets
CPython under UNIX
In addition, the book contains instructions for downloading and installing the Python
Persisted Datalanguage and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Writing to files without reading them doesn't do you much good unless you're creating a report of some kind. If
Whether
a sophisticated
computer
usertonew
a seriousHere's how
you want to persist data
so youyou
canare
use
it later, you have
to be able
readtoitprogramming
back into theor
program.
application
developer,
Python
Programming
with
the
Java(TM)
Class
Libraries
will
we read the data that we wrote in the first example (please follow along):
give you insight into the power of Python and the know-how to put it to work.

>>> file = open("\\dat\\hello.txt", "r")


>>> file.read()
'Hello Mars Hello Jupiter'
>>> file.close()

777

Python
with the
A Tutorial for Building
Theread() method
returnsProgramming
a string representing
the Java
contentsClass
of theLibraries:
file.
Web and Enterprise Applications with Jython
By Richard Hightower

Common File Methods


Publisher: Addison Wesley
Pub Date:
28, 2002
The Python file object supports
theJune
methods
shown in the following list:

Table of
Contents
read() read

ISBN: 0-201-61616-5
Pages: 640

in data from the file

Characterized
byofease
use, richness
of expression, and concise syntax, Python has
readline()
read a line
dataoffrom
a file

remained a premier programming language for more than a decade, and is used by
novices
and all
professionals
Inand
particular,
its close
to Java(TM) makes
readlines()
read
the lines inalike.
the file
return them
as arelationship
tuple of strings
the two languages, when used in combination, ideal for Web and distributed enterprise
write()application
write data todevelopment.
a file
This tutorial
with
coverage
of some of the basics of Python programming. Using
writelines()
writebegins
a tuple
of lines
to a file
plenty of skill-building exercises and interactive programming sessions, this book will

seek() move
to a certain
in a file develop an understanding of concepts and practical
help those
new topoint
programming
techniques. For experienced programmers, the book demonstrates Python's breadth of

tell() determine
theand
current
location
in the
capabilities
shows
the ways
thatfile
Python interfaces with Java APIs for professional
application development.
This is only a partial list. You can read about other file object methods in the Python documentation.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

A Little Review
Fundamental programming concepts, including statements, expressions,
interpreters,
and
compilers
You can get a list of methods
that a file
object
supports by using the dir() command like this:
Python basics, including operators, string formatting, namespaces, classes, errors,
>>> file = open("\\dat\\hello.txt")
>>> dir (file) and exceptions
['close', 'closed', 'fileno', 'flush', 'isatty', 'mode', 'name', 'read',
Object-oriented
programming concepts
'readinto', 'readline',
'readlines',
'seek', 'softspace', 'tell',
'truncate', 'write', 'writelines']
File input/output
dir() lists all public members of a class.
Python's intrinsic functions

write() and readline()


Formatting, parsing, and manipulating strings
In our c:\dat\hello.txt example,
we wrote
strings.
Then
used a with
text editor
to read that file and saw that
Interfacing
withthree
the Java
APIs
andwe
working
Java Streams
all three strings were on the same line. Of course, this is a very short file, but if all of the items we wrote to a
Using
andline,
Javathe
Swing
to create
GUIsto read and parse. To avoid this, we can
standard-size file were written
onPython
the same
file would
be hard
write a newline character (\n) at the end of each line to denote that the text that follows begins a new line.
Working with SQL and JDBC(TM)
Let's continue with some examples that demonstrate writing data on separate lines. Follow along in the
Python and Java applets
interactive interpreter.

In addition,
book
First we write three lines
to a filethe
like
this:contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
>>> fname = "c:\\dat\\data.txt"
and numerous code samples make this book a useful learning experience.

>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>

f = open (fname, "w") #open the file in write mode


Whether you
are a sophisticated #write
computer user
programming
or a serious
f.write("line1
\n")
outnewa toline
of text.
application developer, Python Programming
withsignifies
the Java(TM) Class
Libraries will
# the \n
newline
give you insight
Python andout
the know-how
to put it to work.
f.write("line2
") into the power of #write
some text.
f.write(" still line2")
#write out some more text
f.write(" \n")
#write out a newline character
f.write("line3 \n")
#write out a line of text
f.close()
#close the file

777

>>> f = None Python Programming#set


theJava
refClass
to Libraries:
none
with the
A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

Without the newline character, all of the text is on the same line, which you can see by opening the file
(c:\dat\data.txt) and comparing
each
line ofWesley
text with the code that created it.
Publisher:
Addison
2002
f.write("line2 Pub
")Date: June 28,
#write
out some text.
ISBN: 0-201-61616-5
f.write("
still
line2")
#write
out some more text
Table of

Pages: 640
f.write("
#write out a newline character
Contents \n")

Characterized by ease of use, richness of expression, and concise syntax, Python has
a premier
programming
language
for more
than
decade, and is used
by
Now let's reopen ourremained
file in read
mode and
read each line
individually
with
the areadline()
method.
novices and professionals alike. In particular, its close relationship to Java(TM) makes
>>> f = open the
(fname,
"r")
open
the file
inforread
mode
two languages,
when#used
in combination,
ideal
Web and
distributed enterprise
>>> line = f.readline()
# read one line in and store it in line
application development.

>>> line
# line one contains the first line we
This tutorial begins with coverage of# some
of the basics
Python programming.
>>>
wrote.
Noteof "\n"
= "\12" Using
plenty
of
skill-building
exercises
and
interactive
programming
sessions,
this book will
'line1 \ 12'
help
those
new
to
programming
develop
an
understanding
of
concepts
and
practical
>>> print line
# print the line. note that
the newline
techniques.
For
experienced
programmers,
the
book
demonstrates
Python's
breadthline
of
>>>
# is still attatched to the
capabilities
and
shows
the
ways
that
Python
interfaces
with
Java
APIs
for
professional
line1
application development.

>>> f.readline()
#read the second line.
Pythonline2
Programming
with the Java(TM) Class Libraries: A Tutorial for Building Web
'line2
still
\ 12'
and Enterprise Applications
with Jython
covers important
>>> f.readline()
#read
the third
line topics such as:
'line3 \ 12'
>>> f.close()
#close
the file
Fundamental
programming
concepts, including statements, expressions,
>>>
interpreters, and compilers
Python basics, including operators, string formatting, namespaces, classes, errors,
Notice that we have a lot fewer
readline() calls than we had write() calls. This is because
and exceptions
readline() reads a line of text until it hits the newline character, which it interprets as the last character in
the input string.
Object-oriented programming concepts

readlines()

File input/output

Python's intrinsic functions


Thereadlines() method (note plural) reads all of the lines in the file and puts them in a list of strings. To
illustrate, we'll read all of the
lines in the
file at once
with the following
Formatting,
parsing,
and manipulating
stringsinteractive session:

>>> f = open(fname,
"r")with the
#reopen
file with
in Java
read
mode
Interfacing
Java APIs the
and working
Streams
>>> list = f.readlines()
#read in all the lines at once
>>> list
Using Python and Java Swing#display
to create GUIsthe list
['line1 \ 12', 'line2
still line2 \ 12', 'line3 \ 12']
Working with SQL and JDBC(TM)
>>> for line in list:
#print out each line
...
print line
Python and Java applets
...
line1
In addition, the book contains instructions for downloading and installing the Python
line2 still line2
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
line3
and numerous code samples make this book a useful learning experience.
>>>
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

Getting Rid of \n

Publisher:
Addisoncharacter
Wesley when you read in a line. Here's the not very Python way of doing
You may want to dispose
of the newline
Pub Date: June 28, 2002
this:
ISBN: 0-201-61616-5

Table of
>>>
#reopen the file again
f = open("\\dat\\data.txt")
Pages: 640
>>>Contents
line = f.readline()
#read in the line
>>> line
#before
theconcise
newline
Characterized by ease of use,
richness removing
of expression, and
syntax, character
Python has
'line1 \ 12'remained a premier programming language for more than a decade, and is used by

novices and professionals alike. In particular, its close relationship to Java(TM) makes

>>> line = line[0:len(line)-1]


of the
newline
character
the two languages, when used in#chop
combination,
ideal for
Web and distributed
enterprise
>>> line
application development. #After the newline character is gone.
'line1 '
>>> f.close()
#close
the file
This tutorial begins
with coverage
of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
Here's the more Python
help way:
those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
>>> f = open("\\dat\\data.txt")
# reopen the file
capabilities and shows the ways that Python interfaces with Java APIs for professional
>>> line = (f.readline())[:-1]
# read the line and chop
application development.

>>>
>>> line
'line1 '

# the newline character off.

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

We're doing two things at once with this call. We're putting readline() in parentheses and then using the []
operator with slice notation
on the list itprogramming
returns.
Fundamental
concepts, including statements, expressions,
interpreters, and compilers

line = (f.readline())[:-1]
# read the line and chop
# the
newline
character
off.
Python basics,
including
operators,
string formatting,
namespaces, classes, errors,
and exceptions
In case you didn't catch what we just did, here's the same thing in slow motion, reading the second line, with a few
more code steps for clarity.
Object-oriented programming concepts

>>> line2 = f.readline()


# Read in line2.
File input/output
>>> line2 = line2[:-1]
# Using slice notation assign
Python's intrinsic functions
>>>
# line2 to line2 from the first
>>>
# character up to but not including
Formatting, parsing, #
andthe
manipulating
strings
>>>
last character.
>>> line2
# Display line2
Interfacing with the Java APIs and working with Java Streams
'line2 still line2 '
Using Python and Java Swing to create GUIs
For a review of slice notation, go back to Chapters 1,2 and 3.
Working with SQL and JDBC(TM)

read()

Python and Java applets

Let's start a new example


to show
to contains
use read()
. First we'll
create a file and
the hex
In addition,
thehow
book
instructions
for downloading
and write
installing
the digits
Python1
throughF to it. Thenlanguage
we'll openand
thethe
fileJava
(c:\\dat\\read.txt)
in
write
mode.
(Don't
worry
about
hex
for
now; just
Development Kit (JDK). Terminology, definitions, explanations,
follow along.)
and numerous code samples make this book a useful learning experience.

>>> f = open("\\dat\\read.txt",
Whether you are a sophisticated "w")
computer user new to programming or a serious
>>> f.write("0123456789ABCDEF")
application developer, Python Programming with the Java(TM) Class Libraries will
>>> f.close()give you insight into the power of Python and the know-how to put it to work.
That's the setup. Now we'll demonstrate the different ways to use read().

777

>>> f = open("\\dat\\read.txt", "r")


>>> f.read(3)
# Read the first three characters.

'012'

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
f.read(3)ByRichard Hightower
# Read the next three characters in the file.

>>>
'345'

Publisher: Addison Wesley

>>> f.read(4)
'6789'

Table of
Contents
f.read()

>>>
'ABCDEF'

Read
the
Pub Date:#June
28, 2002

next four characters in the file.

ISBN: 0-201-61616-5
Pages: 640

# Read the rest of the file.

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
We can see that read(size) reads a specified number of characters from the file. Note that calling
novices and professionals alike. In particular, its close relationship to Java(TM) makes
read() with no arguments reads the rest of the file and that the second read() starts reading where the first
the two languages, when used in combination, ideal for Web and distributed enterprise
one left off.
application development.

tell() and seek()


This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
those new
totrack
programming
an reading
understanding
ofWhat
concepts
practical
We just saw that thehelp
file object
keeps
of where develop
we left off
in a file.
if weand
want
to move to a
techniques.
For
experienced
programmers,
the
book
demonstrates
Python's
breadth
of our
previous location? For that we need the tell() and seek() methods. Here's an example that
continues
capabilities
and
shows
the
ways
that
Python
interfaces
with
Java
APIs
for
professional
read() example:
application development.

>>> f.seek(0)
#reset the file pointer to 0
Python
Programming
the Java(TM)
>>> f.read() #read in thewith
whole
file Class Libraries: A Tutorial for Building Web
and
Enterprise
Applications
with
Jython
covers important topics such as:
'0123456789ABCDEF'
>>> f.tell()
16

#see where the file pointer is

Fundamental programming concepts, including statements, expressions,


interpreters, and compilers

>>> f.seek(8) #move


theincluding
middle
of the
Pythonto
basics,
operators,
stringfile
formatting, namespaces, classes, errors,
>>> f.tell()
#see
where
the
file
pointer
is
and exceptions
8
Object-oriented programming concepts

>>> f.read()
'89ABCDEF'

#read from the middle of the file to the end


File input/output

Python's
intrinsic
functions
The second line reads in the
whole file,
which
means that the file pointer was at the end. The third line uses
tell() to report where the file pointer was, and then seek() positions the pointer to the middle of the file.
Formatting,
parsing,
and manipulating
strings
Again,tell() reports that
location. To
demonstrate
that read()
picks up from the file pointer's location,
we'll read the rest of the file and display it.
Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs

For Beginners: Try It Out

Working with SQL and JDBC(TM)

If you're sitting therePython


staringand
at the
book
and wondering what I'm talking about, you need to do
Java
applets
three things:
In addition, the book contains instructions for downloading and installing the Python
1. Enter inlanguage
the last example
in the
interactive interpreter,
experimentdefinitions,
with tell()
,
and the Java
Development
Kit (JDK).and
Terminology,
explanations,
seek()
read()
. samples make this book a useful learning experience.
and, and
numerous
code
2. Open the file with your favorite text editor, and count the characters in it.
Whether
a sophisticated
computer user
new atosingle
programming
a serious
3. Move around
theyou
file,are
and
read various characters.
To read
character,orcall
the
application
developer,
Programming with the Java(TM) Class Libraries will
read()
method with
1 as itsPython
argument.
give you insight into the power of Python and the know-how to put it to work.
If you still don't get it, don't worry; we'll cover this more in the next section.

777

Putting It All Together: The Address Book Example

Programming with the Java Class Libraries: A Tutorial for Building


InChapter 4, we usedPython
an address
book application to demonstrate the if,for, and while statements. We're
Web and Enterprise Applications with Jython
bringing it back to review the concepts we've learned so far.
By Richard Hightower

name = "
"
while (name != Publisher:
""): Addison Wesley
Pub Date: June 28, 2002 in the name: ")
name = raw_input("Enter
ISBN:
0-201-61616-5
if
(name
==
""):
Table of

Pages: 640
continue
Contents
elif (name == "quit"):
Characterized
by ease of use, richness of expression, and concise syntax, Python has
break
remained
a
premier
programming language for
a decade,
and is used")
by
phone_number = raw_input("Enter
in more
thethan
phone
number:
novices
and
professionals
alike.
In
particular,
its
close
relationship
to
Java(TM)
address_line1 = raw_input("Enter address line one: ") makes
the two languages, when
in combination, ideal for Web and distributed enterprise
if (address_line1
== used
""):
application
development.
continue
address_line2 = raw_input("Enter address line two: ")
This tutorial begins
with coverage of some of address
the basics of line
Python programming.
address_line3
= raw_input("Enter
three: ")Using
plenty
of
skill-building
exercises
and
interactive
programming
sessions,
this book will
#do something useful with the addresses
help
those
new
to
programming
develop
an
understanding
of
concepts
and
practical
else:
techniques.
For
experienced
programmers,
the
book
demonstrates
Python's
breadth of
print("send the email to Rick")
capabilities
and
shows
the
ways
that
Python
interfaces
with
Java
APIs
for
professional
#emailAddresses("rick_m_hightower@emailcompany.com")
application development.

Organization Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
The first thing we want to do is organize our program to store the data structures, so we'll create a class (the code
is from address1.py).
Fundamental programming concepts, including statements, expressions,
class Address: interpreters, and compilers

def __init__(self, name="", phone_number="", address_lines=[]):


Python basics, including operators, string formatting, namespaces, classes, errors,
self.__name=name
and exceptions
self.__phone_number=phone_number
self.__lines=address_lines

Object-oriented programming concepts


TheAddress class represents an entry in our address book. Later we'll add a __save__ method so we can
writeAddress's contentsFile
out input/output
to a file. Before we do that, though, we need to change the address program to
store the addresses in instances of Address, and we need to store the instances in some collection objectI
Python's intrinsic functions
picked a dictionary. (I also added comments to make the flow of the program clear for those of you who forgot
Chapter 4.) Here's the amended
code (from
address1.py):
Formatting,
parsing,
and manipulating strings

dict = {}
# Interfacing
to holdwith
the
addresses,
i.e.,
the Java
APIs and working
with to
Java hold
Streams
# instances of the Address class
name = "
"
Using Python and Java Swing to create GUIs
while (name != ""):
with the
SQL and
JDBC(TM)
# Get the Working
name of
person
name = raw_input("Enter in the name: ")
Python and Java applets

# if the name is empty then continue at the top of the loop


In addition, the book contains instructions for downloading and installing the Python
# else if the name equal quit then break out of the loop
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
if (name == ""):
and numerous code samples make this book a useful learning experience.
continue
elif (name ==Whether
"quit"):
you are a sophisticated computer user new to programming or a serious
break application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

# Get the phone number for the person


phone_number = raw_input("Enter in the phone number: ")
# Get the address of the person
# If the first address line is blank then continue

777

# with entering
inProgramming
the next with
address
Python
the Java Class Libraries: A Tutorial for Building
# Otherwise
gather Applications
the otherwith
two
address lines
Web and Enterprise
Jython
address_line1ByRichard
= raw_input("Enter
address line one: ")
Hightower
if (address_line1 == ""):
#Create
an address
Publisher: Addison
Wesley object and store
# it in Pub
the
dictionary
Date: June 28, 2002
address = ISBN:
Address(name,
0-201-61616-5 phone_number, [])
Table dict[name]=address
of

Pages: 640
Contents
continue
address_line2Characterized
= raw_input("Enter
address
lineand
two:
")syntax, Python has
by ease of use, richness
of expression,
concise
address_line3remained
= raw_input("Enter
address
line
three:
a premier programming language for more than a decade,")
and is used by
#Create
an
address
object
store
it relationship
in the to
dictionary
novices and professionals
alike. Inand
particular,
its close
Java(TM) makes
address = Address(name,
[address_line1,
address_line2,
address_
the two languages, phone_number,
when used in combination,
ideal for Web and distributed
enterprise
dict[name]=address
application development.
#do something
useful
with the
addresses
This tutorial begins
with coverage
of some
of the basics of Python programming. Using
else:

plenty of skill-building exercises and interactive programming sessions, this book will

print("send
thetoemail
to Rick")
help those new
programming
develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
The code consists ofcapabilities
a while loop
that gathers
addresses
from the
user. Ifwith
the user
a blank
string for the
and shows
the ways
that Python
interfaces
Javaenters
APIs for
professional
name, the loop startsapplication
at the top. If
the
user
returns
a
blank
for
the
first
address
line,
that
line
is
left
off.
Once all
development.
fields have been gathered, we construct an instance of the Address class and store it in the dictionary. As an
exercise, try runningPython
the program
from address1.py.
Programming
with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

File Support
Fundamental programming concepts, including statements, expressions,
The next thing we do is provide
file support
for our program by adding the __save__ method in the
interpreters,
and compilers
Address class. Taking a file object as an argument, __save__ saves members of the class instance to a file.
The following, from address2.py,
Python shows
basics, Address.save
including operators,: string formatting, namespaces, classes, errors,
and exceptions

class Address:
...
Object-oriented programming concepts
...
def save(self,
file):
File input/output
file.write(self.__name + "\n")
Python's intrinsic functions
file.write(self.__phone_number
+ "\n")
# if there are address lines then write them out
Formatting,
parsing, and manipulating strings
# to
the file
if(len(self.__lines)>0):
Interfacing with the Java APIs and working with Java Streams
file.write("true" + "\n")
file.write(`self.__lines`
+ "\n")
Using Python
and Java Swing to create GUIs
As you can see, save writes
all of the
the class. The code checks for any address lines; if there
Working
withmembers
SQL andofJDBC(TM)
aren't any, it just skips writing them. If there are, it writes out "true" to the file and then writes out the address
lines using the string representation
`self.__lines`
.
Python and
Java applets

In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

For Beginners: repr()

Publisher:
Remember the repr()
built-inAddison
functionWesley
from Chapter 6? It prints the string representation of an object so that it
can be rebuilt with a call
the eval
statement.
PubtoDate:
June 28,
2002 Thus, when we do this:
ISBN: 0-201-61616-5

Table of
file.write(`self.__lines`
+ "\n")

Pages: 640
Contents

we get a string representation of the built-in list object. Note that repr() is called when you use back quotes, so
Characterized by ease of use, richness of expression, and concise syntax, Python has
`self__lines`
is equivalent to repr(self.__lines).
remained a premier programming language for more than a decade, and is used by
novices
and professionals
In particular,
its close
relationship
Java(TM)session:
makes
repr() is essential
for reading
the list backalike.
in from
the file. We'll
review
it with thistointeractive
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
>>> list = ["item1",
"item2", "item3"] # create list

>>> list
# show the contents of the list
This tutorial'item3']
begins with coverage of some of the basics of Python programming. Using
['item1', 'item2',

plenty of skill-building exercises and interactive programming sessions, this book will
those new to programming
develop an
understanding
of concepts and practical
>>> string =help
`list`
# return
string
representation
of the list
techniques.
For
experienced
programmers,
the
book
demonstrates
Python's breadth of
>>> type(string)
# show that this is a string
capabilities and shows the ways that Python interfaces with Java APIs for professional
<type 'string'>
application development.

>>> string Python Programming


#print
the string to the console
with the Java(TM) Class Libraries: A Tutorial for Building Web
"['item1', 'item2',
'item3']"
and Enterprise Applications with Jython covers important topics such as:
>>> list2=eval(string)
# use the eval statement to create
>>>
# the
object
fromexpressions,
the string
Fundamental programming concepts,
including
statements,
interpreters, and compilers

>>> list2
# show that the newly created object
Python
basics,
including
operators,
stringlike
formatting,
classes, errors,
>>>
# is
a list
thenamespaces,
other list
and
exceptions
['item1', 'item2', 'item3']
>>> list ==list2Object-oriented programming concepts
1
File input/output

>>> type(list2) Python's intrinsic functions


<jclass org.python.core.PyList at 161274>
Formatting, parsing, and manipulating strings

Writing to the File Interfacing with the Java APIs and working with Java Streams
Using
Python
andeach
Javaaddress
Swing to
The next thing we add is the
ability
to write
outcreate
to theGUIs
file (this example is from address2.py).

dict = {} #to hold


the
Working
withaddresses
SQL and JDBC(TM)
name = "
"
Python and Java applets
while (name != ""):
...
... In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
else:
and#Open
numerous
samples
make
this writing
book a useful learning experience.
upcode
the
file
for
file = open ("\\dat\\address2.txt", "w")
Whether you are a sophisticated computer user new to programming or a serious
#write each address in the dictionary to the file
application developer, Python Programming with the Java(TM) Class Libraries will
for address in dict.values():
give you insight into the power of Python and the know-how to put it to work.
address.save(file)

777

In the else clause of the while loop, we write out the addresses that we collected in the dictionary. First we
open up c:\dat\address2.txt for reading. Then we create a for loop to iterate through the address objects in
dict (the dictionary object). We write out each address instance by calling __save__ and pass it the file

object we opened.

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
program
enter a few addresses, and look at the output from the file; we can compare
By(address2.py),
Richard Hightower

Let's run our


it to the source code that generated it.

Publisher: Addison Wesley

Wait a minute. There's no use writing items to a file unless we're going to read them back, so let's first add
Pub Date: June 28, 2002
another method, read()
, to our class. Here's the code (address3.py Address.read) for showing how to read an
ISBN: 0-201-61616-5
address
instance:
Table of

Contents

Pages: 640

def read(self, file):


""" Characterized by ease of use, richness of expression, and concise syntax, Python has
remained
a premier
programming
language
than a decade,
and isaused
by
The read
method
reads
fields
of for
themore
instance
from
file.
novices
and
professionals
alike.
In
particular,
its
close
relationship
to
Java(TM)
makes
The read method has one argument. The file argument holds
the
two
languages,
when
used
in
combination,
ideal
for
Web
and
distributed
enterprise
the reference to the output file object.
""" application development.
This
with coverage
of some of the basics of Python programming. Using
# tutorial
Read begins
in the
name field.
plenty
of
skill-building
exercises
and
interactive programming sessions, this book will
self.__name = (file.readline())[:-1]
help those new to programming develop an understanding of concepts and practical
techniques.
programmers,
the book
demonstrates Python's breadth of
# ReadForinexperienced
the phone
number
field.
capabilities
and
shows
the
ways
that
Python
interfaces
with Java APIs for professional
self.__phone_number = (file.readline())[:-1]
application development.

# Check to see if the address lines are present.

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
# If the lines are present, read in the address
and Enterprise Applications with Jython covers important topics such as:

# lines string. Use the eval statement to recreate


# the address lines.
if(file.readline()[:-1])
"true":
Fundamental programming==
concepts,
including statements, expressions,
string
=
(file.readline()[:-1])
interpreters, and compilers
self.__lines=eval(string)

Python basics, including operators, string formatting, namespaces, classes, errors,


and exceptions

Scaffolding Code

Object-oriented programming concepts

It's often useful to develop


what's known as scaffolding code to test the code we're writing. One
File input/output
good reason to do so is that testing code in an interactive session can be cumbersome. The while
loop we used abovePython's
to gatherintrinsic
address functions
information isn't a good place for code testing, so we'll add
methods that do nothing but test if a piece of functionality is working. Any method that starts with
the word test is aFormatting,
scaffolding parsing,
method. and manipulating strings

Interfacing with the Java APIs and working with Java Streams
Here we're reading back the fields one by one. We read in the list that contains the three lines in one call to
readline(). Then we Using
use eval to recreate the object. (If this idea seems weird, take another look at the
Python and Java Swing to create GUIs
repr() notebox.)
Working with SQL and JDBC(TM)
Now that we have both the read() and write() methods for Address, let's create some functions to test
them. The following code writes
then reads them back and prints them for display:
Pythonaddresses
and Java and
applets

def test(): In addition, the book contains instructions for downloading and installing the Python
test_write()
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
test_read()
and numerous code samples make this book a useful learning experience.
def test_write():
file =Whether
open("\\dat\\testaddr.txt",
"w")
you are a sophisticated computer user new
to programming or a serious
address
= Address("Rick
Hightower",
"920-555-1212",
["123
application
developer, Python Programming
with the
Java(TM) Class Libraries
will Main St", "A
address.save(file)
give you insight into the power of Python and the know-how to put it to work.
address = Address("Missy Hightower", "920-555-1212", ["123 Main St", "
address.save(file)
address = Address("Martha Hightower", "602-555-1212", ["123 Main St",
address.save(file)

777

address
= Address("Mary
Hightower",
"520-555-1212",
[])
Python
Programming with the
Java Class Libraries:
A Tutorial for Building
address.save(file)
Web and Enterprise Applications with Jython
By Richard Hightower

def test_read():
file = open("\\dat\\testaddr",
"r")
Publisher: Addison Wesley
for index
in
range(0,3):
Pub Date: June 28, 2002
address
= Address()
ISBN: 0-201-61616-5
Table of
address.read(file)

Pages: 640
Contents
print address
Characterized by ease of use, richness of expression, and concise syntax, Python has
If you try to run this code without adding a __str__ method to the Address class, you'll get some very
remained a premier programming language for more than a decade, and is used by
uninteresting and somewhat useless output. Therefore, we'll add __str__ to Address to display a pretty print
novices and professionals alike. In particular, its close relationship to Java(TM) makes
string representation of the address object.
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
class Address:

...
This tutorial begins with coverage of some of the basics of Python programming. Using
...
plenty of skill-building exercises and interactive programming sessions, this book will
def __str__(self):
help those new to programming develop an understanding of concepts and practical
str = self.__name + "\n"
techniques. For experienced programmers, the book demonstrates Python's breadth of
str = str + self.__phone_number + "\n"
capabilities and shows the ways that Python interfaces with Java APIs for professional
for line in self.__lines:
application development.
str = str + line + "\n"
return
str
Python Programming
with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
Having a meaningful string representation of a class instance can make debugging very easy.
When we run our test, we get
the following
output. Eyeball
it forincluding
correctness.
Fundamental
programming
concepts,
statements, expressions,

interpreters, and compilers

>>> from address3 import *


>>> test()
Python basics, including operators, string formatting, namespaces, classes, errors,
Rick Hightower and exceptions
920-555-1212
123 Main St
Object-oriented programming concepts
Antioch Ca, 95432
File input/output

Line 3
Missy Hightower Python's intrinsic functions
920-555-1212
Formatting, parsing, and manipulating strings
123 Main St
Denver Co, 80202 Interfacing with the Java APIs and working with Java Streams
Line 3
Using Python and Java Swing to create GUIs

Martha Hightower
602-555-1212
Working with SQL and JDBC(TM)
123 Main St
Denver Co, 80202 Python and Java applets
Line 3
In addition, the book contains instructions for downloading and installing the Python
language and thefile
Java
Development
Kit (JDK). Terminology, definitions, explanations,
This is what the testaddr.txt
looks
like:
and numerous code samples make this book a useful learning experience.

Rick Hightower
920-555-1212 Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
true
give you
insight into Ca,
the power
of Python'Line
and the know-how
to put it to work.
['123 Main St',
'Antioch
95432',
3']
Missy Hightower
920-555-1212
true
['123 Main St', 'Denver Co, 80202', 'Line 3']

777

Martha Hightower
Python Programming with the Java Class Libraries: A Tutorial for Building
602-555-1212 Web and Enterprise Applications with Jython
true
By Richard Hightower
['123 Main St', 'Denver Co, 80202', 'Line 3']
Mary Hightower Publisher: Addison Wesley
520-555-1212 Pub Date: June 28, 2002
false
ISBN: 0-201-61616-5

Table of
Contents

Pages: 640

Writing Out and Reading the File


Characterized by ease of use, richness of expression, and concise syntax, Python has
a premier
programming
for more
thanto
a decade,
is used byin
Of course, now that remained
we've added
and tested
our readinglanguage
and writing,
we need
put this and
functionality
novices
and
professionals
alike.
In
particular,
its
close
relationship
to
Java(TM)
makes of
getAddresses. Actually, we've already added writing, but we need to be able to write out a dictionary
the
two
languages,
when
used
in
combination,
ideal
for
Web
and
distributed
enterprise
addresses; our writing code does not do any error checking; and the file is getting pretty long. For these reasons,
application
development. . What we'll do is create two functions that read and write out a
we have to add reading
to getAddresses
dictionary of address instances, and we'll add the necessary try...except and try...finally blocks
This tutorial begins with coverage of some of the basics of Python programming. Using
to the code.
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming
develop an understanding of concepts and practical
def readAddresses(filename,
dict):
techniques.
For
experienced
programmers,
the book demonstrates Python's breadth of
"""
capabilities and shows the ways that Python interfaces with Java APIs for professional
development.of addresses.
Read inapplication
a dictionary

This method takes two arguments as follows:


Python Programming
with the
Java(TM) Class
Libraries:
A Tutorial
for Building
Web
filename
holds the
filename
of the
file
to read
in address
and Enterprise Applications
with
Jython
covers
important
topics
such
as:
instances from
dict
holds reference to the dictionary object that
this
function
adds
addresses
Fundamental
programming
concepts,
including
statements,to
expressions,
"""
interpreters, and compilers
file = None #to hold reference to the input file object
# Use
try..finally
block string
to work
with
the file
Python
basics, including operators,
formatting,
namespaces,
classes, errors,
# Ifandyou
can't work with the file for any reason close it
exceptions
try:
#
try programming
to read concepts
in the addresses from the file
Object-oriented
#
if you can't read the addresses then print an
File input/output
error message
try:
Python's
functions
file intrinsic
= open(filename,"r")
#open the file in read mod
strLength=(file.readline())[:-1] # read in the length
Formatting, parsing, and manipulating strings
length = int(strLength)
# convert length to an int
#read
in
the
addresses
from
0 to length
Interfacing with the Java APIs and working with Java Streams
for index in range(0, length):
address=Address()
Using Python
and Java Swing to create GUIs
address.read(file)
Working with
SQL and JDBC(TM)
dict[address.name()]=address

PythonException,
and Java applets error:
except
print error.__class__.__name__
In addition,
the book
contains instructions for downloading and installing the Python
print
error
language
and
the
Java
Development Kit (JDK). Terminology, definitions, explanations,
finally:
and
numerous
code
samples
make this file.close()
book a useful learning experience.
if not (file is None):
def writeAddresses(filename,
dict):
Whether you are a sophisticated computer user new to programming or a serious
"""
application developer, Python Programming with the Java(TM) Class Libraries will
Write the addresses instances in a dictionary to a file.
give you insight into the power of Python and the know-how to put it to work.
writeAddresses has two arguments as follows:
filename
holds the name of the output file
dict
holds the dictionary of address instances
"""

777

file=None
hold the
object A Tutorial for Building
Python#to
Programming
withoutput
the Javafile
Class Libraries:
#try..finally:
try to with
write
the instances to a file.
Web
and Enterprise Applications
Jython
#if
all
else fails then close the file object
By
Richard
Hightower
try:
#
Write the address instances in dict to a file
Publisher:
Addison Wesley
#
specified
by filename.
Pub Date: June 28, 2002
#
If
there
are any errors then print an error message
ISBN: 0-201-61616-5
Table of
try:Pages: 640
Contents
file = open (filename, "w")
length
= of
str(len(dict))
determine
thehasnumber of
Characterized
by ease
use, richness of expression, and #concise
syntax, Python
#
address
instances
in dict
remained a premier programming language for more than a decade, and is used by
file.write(length
+
"\n")
#
write
the
length
of
dict to
novices and professionals alike. In particular, its close relationship to Java(TM) makes
# used
forineach
address
inWeb
dict.values
write out the
the two languages, when
combination,
ideal for
and distributed enterprise
# address instance to the file object
application development.
for address in dict.values():
address.save(file)
This tutorial begins with
coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
except
Exception,error:
help
those new
to programming develop an understanding of concepts and practical
print
error.__class__.__name__
techniques.
For experienced
programmers, the book demonstrates Python's breadth of
print
error
capabilities
and shows
the ways that Python interfaces with Java APIs for professional
finally:
application development.

if(file):file.close()
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
To make the read()
write()
functionswith
workable,
addimportant
the following
andand
Enterprise
Applications
Jythonwe'll
covers
topicsmethod
such as:to the Address
class:

def name(self): Fundamental programming concepts, including statements, expressions,


interpreters, and compilers
return self.__name
Python
basics, including operators, string formatting, namespaces, classes, errors,
name is used as the key into
the dictionary.
and exceptions
I added many comments to the previous methods. Make it a habit to read them and any document strings in the
Object-oriented
programming
concepts
code listings. Consider document
strings and
comments as
part of the text of this book. Also, be sure to amply
comment your own code.
File input/output

Testing

Python's intrinsic functions

So far we've added read and


write functionality
to the
Address strings
class and added functionality for reading in an
Formatting,
parsing, and
manipulating
entire dictionary of addresses and for writing an entire dictionary of address instances. Now we need to update
Interfacing
withfunctions.
the Java APIs
and
Javawe
Streams
getAddresses() to use
all of these
Before
weworking
do that, with
though,
need to test read
Addresses() and writeAddresses(), which means more scaffolding code.
Using Python and Java Swing to create GUIs

def test_read_write():
Working with SQL and JDBC(TM)
"""
Scaffolding code to test reading and writing dictionaries
Python and Java applets
of addresses.
"""
In addition, the book contains instructions for downloading and installing the Python
# populate
a dictionary
with some
sample
data
language
and the Java
Development Kit object
(JDK). Terminology,
definitions,
explanations,
dict={}and numerous code samples make this book a useful learning experience.
address = Address("Rick Hightower", "920-555-1212", ["123 Main St", "An
dict["Rick
= address
WhetherHightower"]
you are a sophisticated
computer user new to programming or a serious
addressapplication
= Address("Missy
Hightower",
"920-555-1212",
["123
developer, Python Programming
with the
Java(TM) Class Libraries
will Main St", "D
dict["Missy
Hightower"]=address
give you insight into the power of Python and the know-how to put it to work.
address = Address("Martha Hightower", "602-555-1212", ["123 Main St", "
dict["Martha Hightower"]=address
address = Address("Mary Hightower", "520-555-1212", [])
dict["Mary Hightower"]=address

777

Python Programming with the Java


for Building
fname="\\dat\\testaddr.txt"
#to Class
holdLibraries:
outputA Tutorial
filename
Web and Enterprise Applications with Jython
By Richard Hightower

# write the dictionary full of addresses out to the file


print "calling writeAddresses"
Publisher: Addison Wesley
writeAddresses(fname,
dict)
Pub Date: June 28, 2002

ISBN:in
0-201-61616-5
# read
the dictionary full of addresses back from
Table of
Pages:
640
#
the
file
we
just
wrote it to
Contents
dict_in = {}
#to hold input addresses
Characterized
by
ease
of
use,
richness
of
expression,
and concise syntax, Python has
print "calling readAddresses"
remained
a
premier
programming
language
for
more
than
a decade, and is used by
readAddresses(fname, dict_in)

novices and professionals alike. In particular, its close relationship to Java(TM) makes
the
two languages,
when used
in combination,
Web and distributed enterprise
#show
that the
input
matchesideal
theforoutput
application
development.
print "Input"

print
print
print

dict_in
This tutorial begins with coverage of some of the basics of Python programming. Using
"Output"
plenty of skill-building exercises and interactive programming sessions, this book will
dict

help those new to programming develop an understanding of concepts and practical


techniques.
experiencedthese
programmers,
the book
#returnForwhether
equal
eachdemonstrates
other Python's breadth of
capabilities
and
shows
the
ways
that
Python
interfaces
with
Java APIs for professional
return dict==dict_in
application development.
Essentially, our scaffolding code populates a Python dictionary with address instances. Then it writes the
Python
with
the Java(TM)
Libraries:
A Tutorial
for Building
Webthem
dictionary to a file and
readsProgramming
it back. Next it
displays
the inputClass
and output
dictionaries
so that
you can test
and
Enterprise
Applications
with
Jython
covers
important
topics
such
as:
visually. Finally it tells us whether the input dictionary is equal to the output dictionary. With the way the code is
written, it should work until we hit the last line.
Fundamental programming concepts, including statements, expressions,
For the last line to work, we need to add a __cmp__ method to our Address class that iterates through all
interpreters, and compilers
items in the dictionary and compares them. If all of the items are equal, __cmp__ returns that the dictionaries
themselves are equal. Here's
how we
add including
__cmp__operators,
to the Address
class:
Python
basics,
string formatting,
namespaces, classes, errors,
and exceptions

def __cmp__(self,other):
"""
Object-oriented programming concepts
Compares one address instance to another.
If the address
instances are equal the __cmp__ returns 0.
File input/output
If the address instances are not equal then we return a
non-zero
value.
Python's
intrinsic functions
"""
parsing,
and manipulating
strings
# To Formatting,
implement
this
all we do
is compare the
# dictionaries of the class
with the
Java APIsof
andthe
working
with Java Streams
# TheInterfacing
__dict__
member
instance
holds all
# of the instance fields in a dictionary
Using Python and Java Swing to create GUIs
return cmp(self.__dict__ ,other.__dict__)
Working with SQL and JDBC(TM)
Python and Java applets
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

__cmp__ and Equality versus Default Object Identity


Addison
Wesley of objects won't work. To prove this, let's do a small
If we don't definePublisher:
__cmp__,
the comparison
Pub Date: June 28, 2002
interactive session.

Table
First of
we define a
Contents

ISBN: 0-201-61616-5

simple
class.
Pages:
640

>>> class
class1:
Characterized by ease of use, richness of expression, and concise syntax, Python has
...
var="hi"
remained a premier programming language for more than a decade, and is used by
...
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
Then we create two instances.
application development.

>>> instance = class1()


This tutorial
with coverage of some of the basics of Python programming. Using
>>> instance2
= begins
class1()
plenty of skill-building exercises and interactive programming sessions, this book will
new to
programming
an understanding
of concepts
practical
The instanceshelp
havethose
the same
values,
yet when develop
we compare
them they aren't
equal (a 0and
value
equals
techniques.
For
experienced
programmers,
the
book
demonstrates
Python's
breadth of
false).
capabilities and shows the ways that Python interfaces with Java APIs for professional
application
>>> instance
== development.
instance2

0
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise
Applications
with Jython
covers
important
as: instance
The default operation
for __cmp
__ is to check
for object
identity.
Thus,topics
if we such
set another
to equal the first and then test for equality, we get a true (1 value).
Fundamental
programming concepts, including statements, expressions,
>>> instance3
= instance
interpreters,
and compilers
>>> instance3
== instance
1

Python basics, including operators, string formatting, namespaces, classes, errors,


exceptions
However, if we don'tand
define
__cmp__, testing for equality is the same as testing for identity. That
means that the following is equivalent to the above code:
Object-oriented programming concepts

>>> instance3 is instance


File input/output
1
Python's intrinsic functions
We can use scaffolding to retest the code whenever we add fields to the Address class or whenever we
Formatting,
parsing, interactive
and manipulating
change our reading and writing.
The following
sessionstrings
demonstrates the use of scaffolding code to
test the reading and writing of dictionaries of addresses:
Interfacing with the Java APIs and working with Java Streams

>>> from address3 import *


Using Python and Java Swing to create GUIs
>>> test_read_write()
calling writeAddresses
Working with SQL and JDBC(TM)
calling readAddresses
Input
Python and Java applets
{'Rick Hightower': <address3.Address instance at 60188>, 'Martha Hightower':
Output
In addition, the book contains instructions for downloading and installing the Python
{'Mary Hightower':
<address3.Address
at 5ea58>,
language and
the Java Development Kit instance
(JDK). Terminology,
definitions,'Martha
explanations,Hightower':
1
and numerous code samples make this book a useful learning experience.
As you can see, our code
passed
the functioncomputer
returned user
true. new
This to
means
that everyoraddress
in the output
Whether
youbecause
are a sophisticated
programming
a serious
dictionary is equal toapplication
every address
in
the
input
dictionary.
developer, Python Programming with the Java(TM) Class Libraries will

give you insight into the power of Python and the know-how to put it to work.

The Full address3.py Code

777

Now it seems that we have everything we need to run our program, but first let's see all of address3.py, including
the scaffolding code.

Python Programming with the Java Class Libraries: A Tutorial for Building

class Address:
Web and Enterprise Applications with Jython
"""This
class
represents an entry in an address book"""
By Richard
Hightower

#Constructor
Publisher: Addison Wesley
def __init__(self, name="", phone_number="", address_lines=[]):
Pub Date: June 28, 2002
"""
ISBN: 0-201-61616-5
The Table
constructor
takes three arguments:
of

Pages: 640
Contents
name to hold the persons name
(string)
phone_number to hold the persons phone number (string)
Characterized by ease of use, richness of expression, and concise syntax, Python has
address_lines to hold the address of the person (list)
remained a premier programming language for more than a decade, and is used by
"""
novices and professionals alike. In particular, its close relationship to Java(TM) makes
# assign the name, phone_number and address_lines to the
the two languages, when used in combination, ideal for Web and distributed enterprise
# instance variables
application development.
# __name, __phone_number, and __lines
This tutorial begins with coverage of some of the basics of Python programming. Using
self.__name=name
plenty
of skill-building exercises and interactive programming sessions, this book will
self.__phone_number=phone_number
help
those new to programming develop an understanding of concepts and practical
self.__lines=address_lines
techniques.
For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
#Methods
application
development.

def save(self, file):


""" Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
Python
The
save Applications
method saves
thecovers
instance
out such
to as:
a file.
and
Enterprise
with Jython
important topics
The save method has one argument.
file
holds the reference to a file object.
""" Fundamental programming concepts, including statements, expressions,
interpreters,
and compilers
# write
the __name and __phone_number instance variables
# to the file. each variable is on its own line.
Python basics, including operators,
formatting, namespaces, classes, errors,
file.write(self.__name
+ string
"\n")
and
exceptions
file.write(self.__phone_number + "\n")
# if there are address lines then write them out to the f
Object-oriented programming concepts
# Since these lines are optional, write "true" if they ar
# present and "false" if they are not present.
File input/output
if(len(self.__lines)>0):
file.write("true"
+ "\n")
Python's
intrinsic functions
file.write(`self.__lines` + "\n")
parsing, and manipulating strings
elseFormatting,
:
file.write("false\n")
Interfacing
with the Java APIs and working with Java Streams
def read(self,
file):
"""
and Java
Swing to
create GUIs
The Using
readPython
method
reads
fields
of the instance from a file.
The Working
read method
has
one
argument.
with SQL and JDBC(TM)
file
holds the reference to the output file object
""" Python and Java applets
# Read in the name field.
(file.readline())[:-1]
Inself.__name
addition, the book=contains
instructions for downloading and installing the Python
in the phone
number
field.
language and#theRead
Java Development
Kit (JDK).
Terminology,
definitions, explanations,
self.__phone_number
and
numerous code samples make=this(file.readline())[:-1]
book a useful learning experience.
# Check to see if the address lines are present.
Whether you#areIf
a sophisticated
computer
user new read
to programming
serious
lines are
present,
in theor aaddress
lines string.
application developer,
Pythoneval
Programming
with the Java(TM)
Class Libraries
will
# Use the
statement
to recreate
the address
lines.
give
you insight into the power of Python and
know-how to put it to work.
if(file.readline()[:-1])
== the
"true":
string = (file.readline()[:-1])
self.__lines=eval(string)

777

def name(self): return self.__name

Python Programming with the Java Class Libraries: A Tutorial for Building
def __cmp__(self,
other):
Web and Enterprise Applications with Jython
"""
By Richard Hightower
Compares one address instance to another.
If the address instances are equal the __cmp__ returns 0.
Publisher: Addison Wesley
If the address instances are not equal then we return a non-zero
Pub Date: June 28, 2002
"""
ISBN: 0-201-61616-5
# toTable
implement
this,
__cmp__ compares the dictionaries of
of

Pages:
# two
instances. The 640
__dict__ holds all of the members.
Contents
return cmp(self.__dict__ ,other.__dict__)

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming
for more than a decade, and is used by
def __hash__(self):
return language
hash(self.__name)
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
def __str__(self):
application
development.
str = self.__name
+ "\n"

str = str + self.__phone_number + "\n"

This tutorial begins with coverage of some of the basics of Python programming. Using
for line in self.__lines:
plenty of skill-building exercises and interactive programming sessions, this book will
str = str + line + "\n"
help those new to programming develop an understanding of concepts and practical
return str
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
def getAddresses():
application development.

dict = {}

#to hold the addresses

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
# Enterprise
Call read
addresses
to covers
get important
the dictionary
and
Applications
with Jython
topics such as: of addresses

# from the file


readAddresses("c:\\dat\\addressbook.txt", dict)

Fundamental programming concepts, including statements, expressions,


name = " "interpreters, and compilers

while (name != ""):


Python#basics,
operators,
Get including
the name
of string
the formatting,
person namespaces, classes, errors,
and
exceptions
name = raw_input("Enter in the name: ")
# if the name is empty then continue at the top of the lo
Object-oriented
programming
concepts quit then break out of the loop
# if the
name equals
if (name
== ""):
File input/output
continue
elifPython's
(name
== functions
"quit"):
intrinsic
break
Formatting, parsing, and manipulating strings

#Get the phone number for the person


Interfacing with =theraw_input("Enter
Java APIs and working with
Streams
phone_number
inJava
the
phone number: ")
Using #Python
Javaaddress
Swing to create
Getand
the
of GUIs
the person

address_line1 = raw_input("Enter address line one: ")


Working with SQL and JDBC(TM)

IfJava
the
first address line is blank then continue with
Python#and
applets

# entering in the next address


# book
Otherwise
gather for
the
other and
twoinstalling
address
lines
In addition, the
contains instructions
downloading
the Python
if
(address_line1
==
""):
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.

# Create an address object and store it in the


# dictionary
Whether you are a sophisticated
computer user new to programming or a serious
addressPython
= Address(name,
[]) will
application developer,
Programming with thephone_number,
Java(TM) Class Libraries
dict[name]=address
give you insight
into the power of Python and the know-how to put it to work.
continue

777

address_line2 = raw_input("Enter address line two: ")


address_line3 = raw_input("Enter address line three: ")

Python Programming
with
Java Class
Libraries:
A Tutorial
Building
# Create
antheaddress
object
and
storeforit
in the dictionary
Web and Enterprise Applications with Jython
lines = [address_line1, address_line2, address_line3]
By Richard Hightower

address = Address(name, phone_number, lines)


dict[name]=address
Wesley
# Publisher:
Write Addison
the addresses
we created and the ones that
Pub
Date:
June
28,
2002
# we read back to the file
ISBN: 0-201-61616-5
writeAddresses("c:\\dat\\addressbook.txt",dict)
Table of
Contents

Pages: 640

test_read()

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
def test_write():
and professionals alike. In particular, its close
file =novices
open("\\dat\\testaddr.txt",
"w")relationship to Java(TM) makes
the
two
languages,
when
used
in
combination,
ideal
for Web and distributed ["123
enterpriseMain St", "A
address = Address("Rick Hightower", "920-555-1212",
application
development.
address.save(file)

address = Address("Missy Hightower", "920-555-1212", ["123 Main St", "


This tutorial begins with coverage of some of the basics of Python programming. Using
address.save(file)
plenty
skill-building exercises and
interactive programming
sessions, this book
will
address
= ofAddress("Martha
Hightower",
"602-555-1212",
["123
Main St",
help
those
new
to
programming
develop
an
understanding
of
concepts
and
practical
address.save(file)
techniques.
For experienced programmers,
the book
demonstrates Python's breadth
address
= Address("Mary
Hightower",
"520-555-1212",
[]) of
capabilities
and
shows
the
ways
that
Python
interfaces
with
Java
APIs
for
professional
address.save(file)
application development.

def test_read():
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
file =andopen("\\dat\\testaddr.txt",
"r")
Enterprise Applications with Jython covers important topics such as:
for index in range(0,3):
address = Address()
address.read(file)
Fundamental programming concepts, including statements, expressions,
print
address
interpreters,
and compilers
def test_equal():
basics, including operators,
string formatting,
namespaces, classes,["123
errors, Main St",
address1 =Python
Address("Missy
Hightower",
"920-555-1212",
and
exceptions
address2 = Address("Missy Hightower", "920-555-1212", ["123 Main St",
return address1==address2
Object-oriented programming concepts

Using getAddresses()
File input/output
intrinsic
functions
We'll fire up an interactive Python's
session as
an exercise,
and enter three addresses using the getAddresses()
function.
Formatting, parsing, and manipulating strings

>>> from address3 import getAddresses


Interfacing with the Java APIs and working with Java Streams
>>> getAddresses()
Enter in the name: Rick Hightower
Using
Python and925-555-1212
Java Swing to create GUIs
Enter in the phone
number:
Enter address line
one:
Working with SQL and JDBC(TM)
Enter in the name: Kiley Hightower
Enter in the phone
number:
925-555-1212
Python
and Java applets
Enter address line one:
Enter in the Inname:
Hightower
addition,Whitney
the book contains
instructions for downloading and installing the Python
Enter in the language
phone and
number:
925-555-1212
the Java Development
Kit (JDK). Terminology, definitions, explanations,
Enter addressandline
one:
Main
numerous
code123
samples
makeSt.
this book a useful learning experience.
Enter address line two: Antioch, CA
are a sophisticated
Enter addressWhether
lineyou
three:
line 3 computer user new to programming or a serious
Enter in the application
name: developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.
>>> getAddresses()
Enter in the name: Jenna Paul
Enter in the phone number: 925-555-1255
Enter address line one: 125 Main St.
Enter address line two: Antioch, CA

777

Enter addressPython
lineProgramming
three: line
3 Java Class Libraries: A Tutorial for Building
with the
Enter in the Web
name:
quit
and Enterprise
Applications with Jython
By Richard Hightower

Here's the listing for our session:


Publisher: Addison Wesley

4
Pub Date: June 28, 2002
Whitney Hightower
ISBN: 0-201-61616-5
925-555-1212
Table of

Pages:
640
trueContents
['123 Main St.', 'Antioch, CA', 'line 3']
Jenna Paul Characterized by ease of use, richness of expression, and concise syntax, Python has
925-555-1255 remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
true
the two 'Antioch,
languages, whenCA',
used in'line
combination,
['125 Main St.',
3']ideal for Web and distributed enterprise
application
development.
Rick Hightower
925-555-1212
This tutorial begins with coverage of some of the basics of Python programming. Using
false
plenty of skill-building exercises and interactive programming sessions, this book will
Kiley Hightower
help those new to programming develop an understanding of concepts and practical
925-555-1212
techniques. For experienced programmers, the book demonstrates Python's breadth of
false
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.

Persisting Objects with pickle

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
I've got good news for you. There's a way to write Python programs that persist Python objects that's much easier
than the way we've just done it. It's called the pickle module.
Fundamental programming concepts, including statements, expressions,
Let's redefine our Address class and take away its ability to write itself to a file. Then we'll use it to
interpreters, and compilers
demonstratepickle. This example is from address4.Address.
Python basics, including operators, string formatting, namespaces, classes, errors,
class Address: and exceptions

"""This class represents an entry in an address book"""


Object-oriented programming concepts

#Constructor
File input/output
def __init__(self, name="", phone_number="", address_lines=[]):
Python's
intrinsic functions
"""The
constructor
takes three arguments:
name to hold the persons name
(string)
Formatting,
parsing, and manipulating
phone_number
to hold strings
the persons phone number (string)
address_lines to hold the address of the person
(list)
Interfacing with the Java APIs and working with Java Streams
"""
# Python
Assign
theSwing
name,
phone_number
and address_lines to
Using
and Java
to create
GUIs
# the
variables
Working
with instance
SQL and JDBC(TM)
# __name, __phone_number, and __lines.
self.__name=name
Python and Java applets
self.__phone_number=phone_number
In addition, the book contains instructions for downloading and installing the Python
self.__lines=address_lines
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
#Methods

def name(self): return self.__name

Whether you are a sophisticated computer user new to programming or a serious


application developer, Python Programming with the Java(TM) Class Libraries will
def __cmp__(self,other):
give you insight into the power of Python and the know-how to put it to work.
"""

Compares one address instance to another.


If the address instances are equal the __cmp__ returns 0.
If the address instances are not equal then we return
a non-zero value.

777

Python Programming with the Java Class Libraries: A Tutorial for Building

Table of
Contents
def

"""
Web and Enterprise Applications with Jython
# To implement this, all we do is compare the
By Richard Hightower
# dictionaries of the class
# Addison
the __dict__
member of the instance holds
Publisher:
Wesley
# all of the instance fields in a dictionary
Pub Date: June 28, 2002
return
cmp(self.__dict__ ,other.__dict__)
ISBN: 0-201-61616-5
Pages: 640

__hash__(self): return hash(self.__name)


def __str__(self):
Characterized by ease of use, richness of expression, and concise syntax, Python has
str
= self.__name + "\n"
remained a premier programming language for more than a decade, and is used by
str
= str + self.__phone_number + "\n"
novices and professionals alike. In particular, its close relationship to Java(TM) makes
for
line in self.__lines:
the two languages, when used in combination, ideal for Web and distributed enterprise
str = str + line + "\n"
application development.
return str

This tutorial begins with coverage of some of the basics of Python programming. Using
We haven't added anything new to the class. Essentially we've just removed the read() and write()
plenty of skill-building exercises and interactive programming sessions, this book will
methods, and we've taken out the read() and save() methods of the Address class. Now let's show
help those new to programming develop an understanding of concepts and practical
reading and writing this
class to For
a fileexperienced
with the pickle
module. the book demonstrates Python's breadth of
techniques.
programmers,
capabilities and shows the ways that Python interfaces with Java APIs for professional
Import the address4 and pickle modules.
application development.

>>> import address4


Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
>>> import pickle
and Enterprise Applications with Jython covers important topics such as:
Create an instance of Address, and print it to the screen.

Fundamental programming concepts,


including statements,
expressions,
>>> address = address4.Address("Tony
Scalise",
"555-555-3699")
>>> print addressinterpreters, and compilers
Tony Scalise
Python basics, including operators, string formatting, namespaces, classes, errors,
555-555-3699
and exceptions
Open a file for outputting the
address.
Object-oriented
programming concepts

>>> dump_file = open("c:\\dat\\pickle.txt","w")


File input/output
Call the pickle.dump() method, and close the file object.
Python's intrinsic functions

>>> pickle.dump(address,dump_file)
Formatting, parsing, and manipulating strings
>>> dump_file.close()
Interfacing with the Java APIs and working with Java Streams
Read the file back in and print it out to the screen to show that it's the same.
Using Python and Java Swing to create GUIs

>>>
#open the file for reading
>>> address_file Working
= open
"r")
with("c:\\dat\pickle.txt",
SQL and JDBC(TM)

>>>
#load
the
Python
andaddress
Java applets instance from the file
>>> address2 = pickle.load(address_file)
In addition, the book contains instructions for downloading and installing the Python
and the Java instance
Development Kit
>>>
#printlanguage
the address
to (JDK).
the Terminology,
screen definitions, explanations,
and numerous code samples make this book a useful learning experience.
>>> print address2
Tony Scalise
555-555-3699 Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give
insight
of Python
theobject.
know-how to put it to work.
Test to make sure that
theyou
values
are into
equalthe
butpower
that this
isn't theand
same

>>> address == address2


1

777

# the objects are equal

>>> address is
address2
# the
are Anot
theforsame
object
Python
Programming with the
Javaobjects
Class Libraries:
Tutorial
Building
0
Web and Enterprise Applications with Jython
By Richard Hightower

Editing a pickle File


Publisher: Addison Wesley
Date: June
28,the
2002
At this point you may bePub
wondering
what
file created with the pickle module looks like. It's just a text file. In
ISBN:
0-201-61616-5
fact, we
can
edit
it
to
change
its
values.
Here's
the original file:
Table of

Contents

Pages: 640

(iaddress4
Address
Characterized by ease of use, richness of expression, and concise syntax, Python has
p0
remained a premier programming language for more than a decade, and is used by
(dp1
novices and professionals alike. In particular, its close relationship to Java(TM) makes
S'_Address__name'
the two languages, when used in combination, ideal for Web and distributed enterprise
p2
application development.
S'Tony Scalise'
This tutorial begins with coverage of some of the basics of Python programming. Using
p3
plenty of skill-building exercises and interactive programming sessions, this book will
sS'_Address__lines'
help those new to programming develop an understanding of concepts and practical
p4
techniques. For experienced programmers, the book demonstrates Python's breadth of
(lp5
capabilities and shows the ways that Python interfaces with Java APIs for professional
sS'_Address__phone_number'
application development.
p6
S'555-555-3699'
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
p7
and Enterprise Applications with Jython covers important topics such as:
sb.
With your favorite text editor, change 'Tony Scalise' to 'Kelly Pagleochini' (or any name
Fundamental programming concepts, including statements, expressions,
you like), and change the phone number from '555-555-3699' to '555-555-2577'.
interpreters, and compilers

(iaddress4
Python basics, including operators, string formatting, namespaces, classes, errors,
Address
and exceptions
p0
(dp1
Object-oriented programming concepts
S'_Address__name'
p2
File input/output
S'Kelly Pagleochini'
p3
Python's intrinsic functions
sS'_Address__lines'
Formatting, parsing, and manipulating strings
p4
(lp5
Interfacing with the Java APIs and working with Java Streams
sS'_Address__phone_number'
p6
Using Python and Java Swing to create GUIs
S'555-555-2577'
p7
Working with SQL and JDBC(TM)
sb.
Python and Java applets
Now, in an interactive session, we'll show how this changes the object instance.
In addition, the book contains instructions for downloading and installing the Python
First close the file and
reopen and
it. the Java Development Kit (JDK). Terminology, definitions, explanations,
language
and numerous code samples make this book a useful learning experience.

>>> address_file.close()
# close the file
>>> address_file
=
open("c:\\dat\\pickle.txt",
"r")
#or areopen
Whether you are a sophisticated computer user new to programming
serious it
application developer, Python Programming with the Java(TM) Class Libraries will
Then read in the instance using the pickle.load() function.
give you insight into the power of Python and the know-how to put it to work.

>>>
#load the new instance from the file
>>> address3 = pickle.load(address_file)
>>> print address3 # print the new instance out.
Kelly Pagleochini

777

555-555-2577 Python Programming with the Java Class Libraries: A Tutorial for Building
>>> address_file.close()
Web and Enterprise Applications with Jython
By Richard Hightower

I don't recommend that you edit the file that pickle dumps, but it's nice to know that you can. It comes in handy
when you're debugging Publisher:
an application,
andWesley
it's especially useful for viewing dumped files. Are you wondering
Addison
whatS,sS,p0,p1, and the like, mean? They denote the type and placement of the attributes of an object in a
Pub Date: June 28, 2002
file. To learn more about their exact meanings, refer to the pickle Python Library reference.

Table of
Contents

ISBN: 0-201-61616-5

Pages: 640

Writing Out Objects with pickle


Characterized by ease of use, richness of expression, and concise syntax, Python has
With the pickle module
you can
do moreprogramming
than just writelanguage
out classfor
instances
to aafile;
you and
can write
remained
a premier
more than
decade,
is usedout
byany
Python object as well.
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
Open a new file for writing.
application development.

>>> file = open("c:\\dat\\pickle2.txt",


This tutorial begins with coverage of some of "w")
the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
Create a dictionary, populating
it with
string, an integer,
a float,
a list, and another
dictionary,
and write it to a
help those new
to aprogramming
develop
an understanding
of concepts
and practical
file.
techniques. For experienced programmers, the book demonstrates Python's breadth of

>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>

dict = {}capabilities and shows the ways that Python interfaces with Java APIs for professional
application=development.
dict["string"]
"string"
#add a string to the dictionary
dict["int"]=
1
#add
an
int to the dictionary
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
dict["float"]=1.11
#add
a float to the dictionary
and Enterprise Applications with Jython covers important topics such as:
dict["list"]=[1,2,3]
#add a list to the dictionary
dict["dict"]={"martha":"miguel"} #add a dictionary to the dictionary
pickle.dump(dict,file)
#writeincluding
the dictionary
to the file
Fundamental programming concepts,
statements, expressions,
file.close() interpreters, and compilers

The output looks like this: Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions

(dp0
S'int' <- here
is the programming
int item's
key
Object-oriented
concepts
p1
File input/output
I1
<here is the int item's value
sS'string'
<- here is the string item's key
Python's intrinsic functions
p2
g2
Formatting, parsing, and manipulating strings
sS'dict'
<- here is the dictionary item's key
p3
Interfacing with the Java APIs and working with Java Streams
(dp4
S'martha'
Using Python and Java Swing to create GUIs
p5
S'miguel'
Working with SQL and JDBC(TM)
p6
Python
and Java
ssS'float'
<
here
is applets
the float item's key
p7
In addition,
the book
for downloading
F1.11
< here
iscontains
the instructions
float item's
valueand installing the Python
language
and
the
Java
Development
Kit
(JDK).
Terminology,
definitions, explanations,
sS'list'
< here is the list item's key
and
numerous
code
samples
make
this
book
a
useful
learning
experience.
p8
(lp9
Whether you are a sophisticated computer user new to programming or a serious
I1
application developer, Python Programming with the Java(TM) Class Libraries will
aI2
give you insight into the power of Python and the know-how to put it to work.
aI3
as.

777

Of course, we can read back the dictionary object.

Open the file for reading,


andProgramming
read in the pickled
Python
withdictionary.
the Java

Class Libraries: A Tutorial for Building


Web and Enterprise Applications with Jython
#open
the file for reading
By
Richard Hightower

>>>
>>> file = open("c:\\dat\\pickle2.txt","r")
>>>
#load
the dictionary object from the file
Publisher: Addison Wesley
>>> dict2 = pickle.load(file)
Pub Date: June 28, 2002

ISBN: 0-201-61616-5
We can
see of
that the dictionary
read in from the file is equal to the dictionary written to it, but the two are not the
Table

Pages: 640
same object.
Contents

by ease of#use,
richness
of expression,
and concise syntax, Python has
>>> dict2 == Characterized
dict
test
for
equality
remained
a
premier
programming
language
for
more
than
a decade, and is used by
1
novices and professionals alike. In particular, its close relationship to Java(TM) makes
two languages,
when used
in combination,
ideal for Web and distributed
enterprise
>>> dict2 is the
dict
# test:
see
if the dictionaries
are the
same object.
application
development.
0

>>> file.close()

This tutorial begins with coverage of some of the basics of Python programming. Using
plenty
of askill-building
exercises
andinstead
interactive
For efficiency, you can
write
pickled object
as a binary
of a programming
text image: sessions, this book will
help those new to programming develop an understanding of concepts and practical
>>> file = open("c:\\dat\\pickle3.bin","w")
techniques. For experienced programmers, the book demonstrates Python's breadth of
>>> pickle.dump(dict,file,1)
capabilities and shows the ways that Python interfaces with Java APIs for professional
>>> file.close()
application development.

>>>
>>>
>>>
>>>
(1,

file = open("c:\\dat\\pickle3.bin","r")
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
dict3 = pickle.load(file)
and Enterprise Applications with Jython covers important topics such as:
file.close()
dict==dict3, dict is dict3
0)

Fundamental programming concepts, including statements, expressions,


interpreters,
and compilers
The above session is a lot like
the one before
it. The main difference is the third argument to the

pickle.dump() function. We passed it a true (nonzero) value to denote that we wanted this written in

Python basics, including operators, string formatting, namespaces, classes, errors,


binary mode. Of course, looking at this file with a text editor won't do you any good because you need a utility to
and exceptions
view binary files. Here's what it would look like. (You may not know how to read it, but at the least you can see
that it's much harder to readObject-oriented
and edit than the
text mode.) concepts
programming

0FBD:0100
0FBD:0110
0FBD:0120
0FBD:0130
0FBD:0140
0FBD:0150
0FBD:0160

7D
74
03
6D
71
08
75

71
72
7D
69
07
5D
08

00
28 55 03 69 6E-74 71 01 4B 01 55 06
File input/output
69 6E 67 71 02 68-02 55 04 64 69 63 74
71
04 intrinsic
55 06functions
6D 61-72 74 68 61 71 05 55
Python's
67 75 65 6C 71 06-73 55 05 66 6C 6F 61
Formatting,
and0D-0A
manipulating
46
31 2Eparsing,
31 31
55 strings
04 6C 69 73 74
71 09 28 4B 01 4B-02 4B 03 65 75 2E 00
Interfacing
Java04-74
APIs and04
working
with 00
Java 40
Streams
F7
06 23with
D3the00
81 CD
C6

73
71
06
74
71
02
06

} q.(U.intq.K.U.s
tringq.h.U.dictq
.} q.U.marthaq.U.
miguelq.sU.float
q.F1.11..U.listq
.]q.(K.K.K.eu...
u...#...t....@..

Using Python and Java Swing to create GUIs

pickling an Object to a String

Working with SQL and JDBC(TM)


In addition to reading and writing to files, you can read and write to strings. Instead of the dump() function,
Python(note
and Java
applets
you use the dumps() function
plural),
as follows.
addition,
the book contains instructions for downloading and installing the Python
Dump the dictionaryIninto
a text string.
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
>>> string = and
pickle.dumps(dict)
numerous code samples make this book a useful learning experience.
you are
a sophisticated computer user new to programming or a serious
Dump the dictionaryWhether
into a binary
string.
application developer, Python Programming with the Java(TM) Class Libraries will
>>> bin_string
give =youpickle.dumps(dict,1)
insight into the power of Python and the know-how to put it to work.
Load the dictionary from the text string.

777

>>> dict4 = pickle.loads(string)

Load the dictionary from


the Programming
binary string.
Python

>>> dict5 =

with the Java Class Libraries: A Tutorial for Building


Web and Enterprise Applications with Jython
pickle.loads(bin_string)
By Richard Hightower

Check to see if the loaded dictionaries are equal to the dumped dictionary.
Publisher: Addison Wesley

Pub Date:
June 28,
>>> dict == dict4,
dict
== 2002
dict5
ISBN: 0-201-61616-5
(1, Table
1) of

Pages: 640

Contents

Check to see if the loaded dictionaries have the same identity as the dumped dictionary.
Characterized by ease of use, richness of expression, and concise syntax, Python has
>>> dict is dict4,
dict5 language for more than a decade, and is used by
remained adict
premieris
programming
(0, 0)
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
Earlier we said that binary
modedevelopment.
is more efficient than text mode. The question is how much. We can find out by
application
comparing the size of the binary string to the size of the text string from the last example.
This tutorial begins with coverage of some of the basics of Python programming. Using
>>> len(string),
plenty oflen(bin_string)
skill-building exercises and interactive programming sessions, this book will
(129, 93)
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
In this example, binary mode is 40 percent more efficient than text mode. But of course more than just size
capabilities and shows the ways that Python interfaces with Java APIs for professional
efficiency is involved. When you use text mode, the pickle module has to convert text strings into their binary
application development.
equivalents; if you use binary mode, less conversion is necessary.

pickle and

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise
Applications
Jython covers important topics such as:
the
Address
Bookwith
Application

Now that we have a handleFundamental


on the pickleprogramming
module, we can
changeincluding
our address
book program
to use it. Here's the
concepts,
statements,
expressions,
listing for address4 (areas interpreters,
of interest areand
highlighted
in
bold):
compilers

class Address: Python basics, including operators, string formatting, namespaces, classes, errors,
"""This class
represents an entry in an address book"""
and exceptions
#Constructor
def __init__(self,
phone_number="", address_lines=[]):
Object-oriented name="",
programming concepts
"""
File input/output
The constructor takes
three arguments:
name to hold the persons' name
(string)
Python's
intrinsic functions to hold the persons' phone number (string)
phone_number
address_lines to hold the address of the person (list)
""" Formatting, parsing, and manipulating strings
# assign the name, phone_number and address_lines to the
Interfacing with the Java APIs and working with Java Streams
# instance variables
__name,
Using #Python
and Java__phone_number,
Swing to create GUIs and __lines
self.__name=name
self.__phone_number=phone_number
Working with SQL and JDBC(TM)
self.__lines=address_lines
Python and Java applets

#Methods
In addition, the book contains instructions for downloading and installing the Python
language and the Java
Development
Kit (JDK). Terminology, definitions, explanations,
def name(self):
return
self.__name
and
numerous
code
samples
make
this
book a useful learning experience.
def __cmp__(self,other):

"""

Whether you are a sophisticated computer user new to programming or a serious


Compares one address instance to another.
application developer, Python Programming with the Java(TM) Class Libraries will
If the address instances are equal the __cmp__ returns 0.
give you insight into the power of Python and the know-how to put it to work.

If the address instances are not equal then we return a non-zero


value.
"""
# to implement this all we do is compare the dictionaries
# the class. the __dict__ member of the instance holds al

777

# of the
instance
fields
in aA Tutorial
dictionary.
Python Programming
with
the Java Class
Libraries:
for Building
return
cmp(self.__dict__
Web
and Enterprise
Applications with ,other.__dict__)
Jython
__hash__(self):
return hash(self.__name)
By Richard Hightower

def
def __str__(self):
str
= self.__name
Publisher:
Addison Wesley + "\n"
str
=
str
self.__phone_number
+ "\n"
Pub Date: June+28,
2002
for ISBN:
line0-201-61616-5
in self.__lines:
Table of
str = str + line + "\n"
Pages: 640
Contents
return str

Characterized by ease of use, richness of expression, and concise syntax, Python has

def readAddresses(filename):
remained a premier programming language for more than a decade, and is used by
importnovices
pickle
and professionals alike. In particular, its close relationship to Java(TM) makes
""" the two languages, when used in combination, ideal for Web and distributed enterprise
Read in
a dictionary
application
development. of addresses.
This method takes two arguments as follows:
filename
holds
ofprogramming.
the fileUsing
to read in
This
tutorial begins with coverage
of somethe
of thefilename
basics of Python
address
instances
from
plenty of skill-building exercises and interactive
programming
sessions,
this book will
""" help those new to programming develop an understanding of concepts and practical
file =techniques.
None For #to
holdprogrammers,
reference
to the
inputPython's
file breadth
object
experienced
the book
demonstrates
of
capabilities and shows the ways that Python interfaces with Java APIs for professional
# try..finally
application
development. to work with the file

# if you can't work with the file for any reason close it
try: Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise
with Jython
coversaddresses
important topicsfrom
such as:the file
# Applications
try to read
in the
# if you can't read addresses then print an error message
try:
Fundamental
concepts, including statements,
expressions,
file programming
= open(filename,"r")
#open the
file in read mode
interpreters,
dictand
= compilers
pickle.load(file)
return dict
Python basics, including operators, string formatting, namespaces, classes, errors,
except
Exception, error:
and exceptions
print error.__class__.__name__
print error
Object-oriented
programming concepts
return {}
finally: File input/output
if not (file is None): file.close()
Python's intrinsic functions

def writeAddresses(filename, dict, bin=0):


Formatting, parsing, and manipulating strings
import pickle
"""
Interfacing with the Java APIs and working with Java Streams
Write the addresses instances in a dictionary to a file.
writeAddresses
hasSwing
twotoarguments
Using Python and Java
create GUIs as follows:
filename
holds the name of the output file
dict
holds the dictionary of address instances
Working
with SQL and JDBC(TM)
bin
whether to use binary mode or not for the pi
"""
Python and Java applets
file=None
#to hold the output file object
In#addition,
the book contains
instructions
for downloading
and installing
try..finally:
try
to write
the instances
totheaPython
file.
language
and theelse
Java Development
Kit (JDK).
Terminology,
definitions,
explanations,
# if all
fails then
close
the file
object
try: and numerous code samples make this book a useful learning experience.
# Write the address instances in dict to a file
Whether you#arespecified
a sophisticated by
computer
user new to programming or a serious
filename.
application developer,
Python
Programming
with the Java(TM)
Class Libraries
will
# If there are any errors
then print
an error
message
give
you
insight
into
the
power
of
Python
and
the
know-how
to
put
it
to
work.
try:
file = open (filename, "w")
pickle.dump(dict, file, bin)
except Exception,error:
print error.__class__.__name__

777

print error
Python Programming
with the Java Class Libraries: A Tutorial for Building
finally:
Web and Enterprise Applications with Jython
if(file):file.close()
By
Richard Hightower

def test_read_write():
"""
Publisher: Addison Wesley
Scaffolding
code
Pub Date: June 28,
2002 to test reading and writing dictionaries of
addresses.
ISBN: 0-201-61616-5
Table """
of

Pages: 640
Contents
# populate a dictionary object with some sample data
dict={}
Characterized by ease of use, richness of expression, and concise syntax, Python has
address
= Address("Rick
Hightower",
"920-555-1212",
["123
Main St", "A
remained
a premier programming
language for more
than a decade, and is used
by
dict["Rick
Hightower"]
=
address
novices and professionals alike. In particular, its close relationship to Java(TM) makes
address
= Address("Missy
["123 Main St", "
the two
languages, when used inHightower",
combination, ideal "920-555-1212",
for Web and distributed enterprise
dict["Missy
applicationHightower"]=address
development.
address = Address("Martha Hightower", "602-555-1212", ["123 Main St",
dict["Martha
This tutorial Hightower"]=address
begins with coverage of some of the basics of Python programming. Using
address
= ofAddress("Mary
Hightower",
"520-555-1212",
[]) will
plenty
skill-building exercises
and interactive programming
sessions, this book
dict["Mary
help thoseHightower"]=address
new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of

fname="c:\\dat\\testaddr.dat"
#tointerfaces
hold with
output
filename
capabilities and shows the ways that Python
Java APIs
for professional
application development.

#write the dictionary full of addresses out to the file


Programming
with the Java(TM) Class Libraries: A Tutorial for Building Web
print Python
"calling
writeAddresses"
and Enterprise Applicationsdict)
with Jython covers important topics such as:
writeAddresses(fname,
#read in the dictionary full of addresses back from the
Fundamental
programming
# file
we just
wrote concepts,
it to including statements, expressions,
interpreters,
and compilers
print "calling
readAddresses"
dict_in = readAddresses(fname) #to hold input addresses
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions

#show that the input matches the output


"Input"
Object-oriented programming concepts
dict_in
"Output"
File input/output
dict
Python'swhether
intrinsic functions
#return
these equal each other
return dict==dict_in
print
print
print
print

Formatting, parsing, and manipulating strings

def test_equal():
Interfacing with the Java APIs and working with Java Streams
address1 = Address("Missy Hightower", "920-555-1212", ["123 Main St",
address2 =Using
Address("Missy
Hightower",
Python and Java Swing
to create GUIs "920-555-1212", ["123 Main St",
return address1==address2
Working with SQL and JDBC(TM)
You have to notice that the pickle version is much shorter than the original (address3.py). Shorter is better
because less code to write means
maintain.
Pythonless
andcode
Java to
applets
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Python allows you to read and write to files. The Python file object, which is built into the language, supports the
following methods: Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.
read() read in data from a file

Summary

777

readline() read a line of data from a file


readlines() read all the lines in the file and return the lines as a list of strings

Programming
with the Java Class Libraries: A Tutorial for Building
write()Python
write data
to a file
Web and Enterprise Applications with Jython
By Richard
Hightower
writelines()
write
a sequence of lines to a file

seek() movePublisher:
to a certain
point inWesley
a file
Addison
Pub Date: June 28, 2002

tell() determine
the current
location in the file
ISBN:
0-201-61616-5

Table of

Pages: 640

PythonContents
makes working with files straightforward. In addition, its pickle and cPickle modules allow the persisting
of objects to a file or string and make for speedy development of persisted class data.
Characterized by ease of use, richness of expression, and concise syntax, Python has
remainedon
a premier
programming
language
more 4.
than
decade,
and is
used
by as using
In this chapter, we expanded
the address
book example
from for
Chapter
Wea also
covered
such
issues
novices
and
professionals
alike.
In
particular,
its
close
relationship
to
Java(TM)
makes
__str__ and __repr__ with class instances. If you followed along with our expansion of the address
book
the
two
languages,
when
used
in
combination,
ideal
for
Web
and
distributed
enterprise
program to read and write files, you reviewed a lot of the first seven chapters of the book.
application development.

CONTENTS
This tutorial begins with coverage
of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
Object-oriented programming concepts
File input/output
Python's intrinsic functions
Formatting, parsing, and manipulating strings
Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs
Working with SQL and JDBC(TM)
Python and Java applets
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
CONTENTS
Web and Enterprise Applications with Jython
By Richard Hightower

Chapter 9. Built-In
Functions
Publisher: Addison Wesley
Pub Date: June 28, 2002

Conversion
ISBN: 0-201-61616-5
Table of
Namespace: dir(),Pages:
globals(),
640 locals(), vars()
Contents
Type Checking: callable(), type()
Operations Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
Advanced Topic:
Functional Programming
novices and professionals alike. In particular, its close relationship to Java(TM) makes
Advanced exec
and
eval
the two languages,
when used in combination, ideal for Web and distributed enterprise
Summary application development.

Terms in This Chapter


This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
Built-in (intrinsic) function
is operator
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities
interfaces with Java APIs for professional
Bytecode and shows the ways that PythonKeyword
application development.
Collection
Lambda function
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and
important topics such as:
evalEnterprise
statement Applications with Jython covers
Mutable/Immutable
exec statement
Namespace
Fundamental programming concepts, including statements, expressions,
interpreters,
and compilers
Functional
programming
Name/value pair

Python basics, including operators, string


Hashtable
Octalformatting, namespaces, classes, errors,
and exceptions
Hash value
Param eter
Object-oriented programming concepts
Hierarchy
Sequence
File input/output
Identity operator
Python's intrinsic functions
A good part of the simplicity and elegance of Python comes from its built-in (or instrinsic) functions. Many of
Formatting,
parsing,
and manipulating
these are longhand for other
operatorsfor
example,
the cmp()strings
function, which performs the ==,=>,=<,<,
> operations, and the repr() function, which back-quotes an object. When there's no equivalent operator, the
Interfacing
with as
theanJava
APIs and working with Java Streams
built-in function is often referred
to simply
"operator."
Using Python
and Java Swing
to create
Generally, Python built-in functions
are equivalent
to keywords
in GUIs
other languages. One example is C++'s
keywordsizeof() , which determines the size of an array or other structure; its Python counterpart is
Working with SQL and JDBC(TM)
len(), which determines the length of a sequence. Similarly, Java's instanceof() is equivalent to
Python'sisinstance()
.
Python
and Java applets

Conversion In addition, the book contains instructions for downloading and installing the Python

language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Sooner or later you're going to need to convert from one type to another. You may be reading in strings from
files and want to convert
themyou
to text,
before writing
numbers
tonew
a text
you may want
convert them to
Whether
are aor,
sophisticated
computer
user
tofile,
programming
or a to
serious
strings. Python has several
built-in
functions
to
do
this.
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

Converting Numbers to Strings: chr(), str(), hex(), oct()

777

Thechr() function converts a number to a character. Remember that there are no characters in Python, so
chr() returns a single character in a string.

>>> chr(97) Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
'a'
>>> chr(122) ByRichard Hightower
'z'
Publisher: Addison Wesley
Pub Date:
28, 2002
It may seem that you would
rarely June
use chr()
, but wait until Chapter 12, when it will come in handy for
ISBN:
converting a Java binary array
into0-201-61616-5
a Python string.

Table of
Contents

Pages: 640

Thestr() function converts any object, including numeric types, into a string. (Remember, unlike other
languages Python treats
all types asby
objects.)
Characterized
ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
>>> str(1) novices and professionals alike. In particular, its close relationship to Java(TM) makes
'1'
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
Thehex() function converts a number into its hexadecimal equivalent.

This tutorial begins with coverage of some of the basics of Python programming. Using

>>> hex(255)
plenty of skill-building exercises and interactive programming sessions, this book will
'0xff'
help those new to programming develop an understanding of concepts and practical
>>> hex(1l)
techniques. For experienced programmers, the book demonstrates Python's breadth of
'0x1L'

capabilities and shows the ways that Python interfaces with Java APIs for professional
application
development.
Hexadecimal is a base
16 numbering
system used in many computers that allows you to display a byte with two
digits. We'll see it again when we cover the Java InputStream in Chapter 12.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
Enterprise
Applications
with equivalent.
Jython covers
important
such as: system.
Theoct() functionand
converts
a number
into its octal
Octal
is a basetopics
8 numbering

>>> oct(1)
'01'
>>> oct(9)
'011'

Fundamental programming concepts, including statements, expressions,


interpreters, and compilers

Python basics, including operators, string formatting, namespaces, classes, errors,


and exceptions
oct() and hex() work only with integers and longs. They don't work with floats.
Object-oriented programming concepts
You probably won't use chr(),oct(), or hex() very much, if at all, but str() you'll use a great deal.
File input/output

Converting Strings to Numbers: float(), int(), long(), ord()


Python's intrinsic functions
Thefloat() function converts a string to a float.
Formatting, parsing, and manipulating strings

>>> f = float("1.1")
Interfacing with the Java APIs and working with Java Streams
>>> type(f)
<jclass org.python.core.PyFloat
at 1662336>
Using Python and Java Swing to create GUIs
>>>
Working with SQL and JDBC(TM)
Theint() function converts strings to integers.
Python and Java applets

>>> str = "1"


>>> num = int(str)
In addition, the book contains instructions for downloading and installing the Python
>>> type(num)language and the Java Development Kit (JDK). Terminology, definitions, explanations,
<jclass org.python.core.PyInteger
at book
3414368>
and numerous code samples make this
a useful learning experience.
>>>
Whether you are a sophisticated computer user new to programming or a serious
Thelong() function
converts developer,
a string intoPython
a long.Programming with the Java(TM) Class Libraries will
application
give you insight into the power of Python and the know-how to put it to work.

>>> long("12345678901234567890")
12345678901234567890L

777

Theord() function converts a character (that is, a string with one element) into its ASCII value.

>>> ord("A"),Python
ord("Z")
Programming with the Java Class Libraries: A Tutorial for Building
(65, 90)
Web and Enterprise Applications with Jython
>>>
By Richard Hightower
Publisher:
Wesley
Converting Numbers
toAddison
Different
Numeric Types: coerce()
Pub Date: June 28, 2002
ISBN: 0-201-61616-5
Thecoerce() function converts
one numeric type into another, or rather it changes the type of one value to
Table of

Pages: 640
another
type.
Actually,
coerce()
doesn't change the value but returns it in a tuple.
Contents

Declare some variables


to convert. by ease of use, richness of expression, and concise syntax, Python has
Characterized
remained a premier programming language for more than a decade, and is used by
>>> myintegernovices
= 1 and professionals
# alike.
an In
int
particular, its close relationship to Java(TM) makes
>>> mylong = the
1ltwo languages, when#used
a in
long
combination, ideal for Web and distributed enterprise
>>> myfloat =application
1.0
development.# a float

>>> mystring = "1"

# a non-numeric object

This tutorial begins with coverage of some of the basics of Python programming. Using
Coerce an integer into
a long.
plenty
of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
>>> coerce(mylong,
myinteger)
techniques. For experienced programmers, the book demonstrates Python's breadth of
(1L, 1L)
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
Do the same as above, but swap the position of the integer and the long.
Python Programming
>>> coerce(myint,
mylong) with the Java(TM) Class Libraries: A Tutorial for Building Web
and
Enterprise
Applications with Jython covers important topics such as:
(1L, 1L)
Coerce an integer into a float.
Fundamental programming concepts, including statements, expressions,

and compilers
>>> coerce(myint,interpreters,
myfloat)
(1.0, 1.0)
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
Coerce a long into a float. (The
long has to be in the range of allowable values for the Float type.)
Object-oriented
programming concepts
>>> coerce(mylong,
myfloat)
(1.0, 1.0)
File input/output

coerce() works only with


numeric types. It won't work with strings, as you can see here:
Python's intrinsic functions
>>> coerce(mystring,
myint)
Formatting, parsing, and manipulating strings
Traceback (innermost last):
File "<interactive
input>",
line
in ? with Java Streams
Interfacing
with the Java
APIs 0,
and working
TypeError: number coercion failed
>>>
Using Python and Java Swing to create GUIs
To convert an integer or a long
into awith
float,
do and
this:JDBC(TM)
Working
SQL

>>> myint = 10 Python and Java applets


>>> myint = coerce(1.0, 10)[1]
In addition, the book contains instructions for downloading and installing the Python
>>> print myint
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
10.0
and numerous code samples make this book a useful learning experience.

Converting Sequences:
list(), tuple()
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
Remember that tuples
areyou
immutable,
which
you can't
to them.
If you
to add items to
give
insight into
the means
power that
of Python
andadd
the items
know-how
to put
it toneed
work.
a sequence, you have to use a list. Conversely, you can't use a list as a key into a dictionary. Since dictionaries
store items based on a hashtable that uses the hash value of the key, they need types that won't changethat is,
immutable tuples. Python has two built in functions to deal with these problems.

777

Thelist() function
converts
an immutable
sequence
(such Class
as a tuple)
into a mutable
onefor
(such
as a list).
Python
Programming
with
the Java
Libraries:
A Tutorial
Building
Here's an example. Web and Enterprise Applications with Jython
By Richard Hightower

Create a tuple.
Publisher: Addison Wesley

>>> tup = (1,2,3,4,5,6,7,8,9)

Pub Date: June 28, 2002

ISBN:fail).
0-201-61616-5
Try toTable
add something
to it (you'll
of

Contents

Pages: 640

>>> tup.append(1)
Traceback (innermost
Characterized last):
by ease of use, richness of expression, and concise syntax, Python has
File "<stdin>",
1,programming
in ?
remainedline
a premier
language for more than a decade, and is used by
AttributeError:
'tuple'
object
no attribute
'append'
novices
and professionals
alike.has
In particular,
its close relationship
to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
Convert the tuple, tup
, into a list,
ls.
application
development.

>>> ls =list(tup)
This tutorial begins with coverage of some of the basics of Python programming. Using
>>> ls.append(10)
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
Thetuple() function
convertsFor
a mutable
sequence
into a tuple.
our last
example
to of
techniques.
experienced
programmers,
theWe'll
bookcontinue
demonstrates
Python's
breadth
demonstrate how it works.
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
Convertls to a tuple, tup, and display it.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web

>>> tup=tuple(ls)
and Enterprise Applications with Jython covers important topics such as:
>>> tup
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
>>>
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers

Python basics, tuple()


including operators,
formatting, namespaces, classes, errors,
and string
list()
and exceptions
Thetuple() and list() functions take any kind of sequence. Here's what happens if you
Object-oriented programming concepts
pass tuple() a tuple:
File input/output
>>> tup = (1,2,3)
>>> id(tup),Python's
id(tuple(tup))
intrinsic functions
(201160, 201160)
Formatting, parsing, and manipulating strings

>>> tup is tuple(tup)


1
Interfacing with the Java APIs and working with Java Streams
As you can see, the Using
id of Python
tup and
id Swing
of the tuple
returned
andtheJava
to create
GUIsfrom tuple() are the same.
We can demonstrate this with the identity operator, which returns as a true statement that tup is
tuple(tup). Working with SQL and JDBC(TM)

Python and, Java


applets
If you pass a list to tuple()
you get
a new tuple.
In addition,
the book contains instructions for downloading and installing the Python
>>> lst =
[1,2,3]
languagetuple(lst)
and the Java Development Kit (JDK). Terminology, definitions, explanations,
>>> id(lst),
numerous
code samples make this book a useful learning experience.
(332828, and
(1,
2, 3))
Whetherid(tuple(lst))
you are a sophisticated computer user new to programming or a serious
>>> id(lst),
application
(332828, 321564)developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

>>> lst is tuple(lst)


0

777

Notice that, every time you call list(ls) , you get a new copy of ls.

Converting

Python Programming with the Java Class Libraries: A Tutorial for Building
Web andto
Enterprise
Applications
with Jython
Objects
Strings:
str(), repr()
By Richard Hightower

Thestr() function converts all object types to strings. The repr() function converts all object types to
Publisher:
Addison
strings that might be able
to reconstruct
theWesley
object with a call to eval. Here's an example of both.
Pub Date: June 28, 2002
ISBN:
0-201-61616-5
Create a list, a tuple, a string,
and an
integer object.

Table of
Contents

Pages: 640

>>> list, tuple, string, int = [1,2],(1,2),"12",12


Characterized by ease of use, richness of expression, and concise syntax, Python has
Create a dictionary object
that acontains
list, tuple, string
and for
integer
created.
remained
premierthe
programming
language
moreobjects
than ajust
decade,
and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
applicationofdevelopment.
Show the string representation
the dictionary object.

>>> dict ={"list":list, "tuple":tuple, "string":string, "int":12}

>>> str(dict)This tutorial begins with coverage of some of the basics of Python programming. Using
plenty
of skill-building
exercises
and 'list':
interactive programming
book "will
"{'tuple': (1,
2),
'string':
'12',
[1, 2], sessions,
'int':this12}
help those new to programming develop an understanding of concepts and practical
For experienced
programmers,
the book demonstrates Python's breadth of
Show the repr() techniques.
string representation
of the dictionary
object.
capabilities and shows the ways that Python interfaces with Java APIs for professional
>>> repr(dict)
application development.

"{'tuple': (1, 2), 'string': '12', 'list': [1, 2], 'int': 12} "
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

Namespace: dir(), globals(), locals(), vars()

Fundamental
programming
concepts,
statements,
expressions,
In most languages, the namespace
is decided
at compile
time, andincluding
there is no
way to determine
which variables
interpreters,
andprogram
compilers
are in it unless you try to use
them and the
doesn't compile. With Python, you can see the variables in
the namespace, and you can see what variables a given object exposes.
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions

dir()

Object-oriented programming concepts

dir([object]) returns a list of namespace variables. If no arguments are passed, it returns a list of names
File input/output
in the current namespace; otherwise,
it returns a list of an object's attribute names.
Python'sshowing
intrinsic what's
functions
Here are two examples of dir()
in the current namespace in a function and in a module,
respectively:
Formatting, parsing, and manipulating strings

>>> var1, var2, var3, var4 = 1,2,3,4


Interfacing with the Java APIs and working with Java Streams
>>> dir()
['__builtins__', 'var1', 'var2', 'var3', 'var4']
Using Python and Java Swing to create GUIs
>>> def func(lvar1, lvar2,lvar3,lvar4):
...
return dir()
Working with SQL and JDBC(TM)
...
Python and Java applets

>>> func(var1,var2,var3,var4)
['lvar1', 'lvar2',
'lvar4']
In addition,'lvar3',
the book contains
instructions for downloading and installing the Python
>>>
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Here's an example showing dir() inspecting a module and a class.
Whether you are a sophisticated computer user new to programming or a serious
Inspect the attributesapplication
of the sys module.
developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

>>> import sys


>>> dir(sys)
['__doc__', '__name__', '__stderr__', '__stdin__', '__stdout__', 'argv', 'bui

777

Inspect the Exception class.

Python Programming with the Java Class Libraries: A Tutorial for Building

>>> dir(Exception)
Web and Enterprise Applications with Jython
['__doc__', '__getitem__',
'__init__', '__module__', '__str__']
By Richard Hightower
>>> type (Exception)
#just to show that it is a class
Publisher: Addison Wesley
<jclass org.python.core.PyClass
at 4958626>
Pub Date: June 28, 2002
ISBN: 0-201-61616-5
InspectTable
an instance
of the Exception
class.
of

Contents

Pages: 640

>>> e = Exception()
>>> dir (e) Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
['args']

globals()

novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.

With a few exceptions,


globals()
function
is similar
to of
dir()
. It always
returns
the variableUsing
names
Thisthe
tutorial
begins with
coverage
of some
the basics
of Python
programming.
defined in the currentplenty
module,
and it returnsexercises
a dictionary
the name
in the name/value
is thewill
name of
of skill-building
andwhere
interactive
programming
sessions,pairs
this book
the object (the variable
is the object
itselfan(the
value). Evenofifconcepts
you call globals()
helpname)
thoseand
newthe
to value
programming
develop
understanding
and practical in a
function call, it returns
the globalFor
variables
for that
module.
techniques.
experienced
programmers,
the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
>>> gvar1,gvar2,gvar3=1,"two",[3,3,3]
application development.

>>> def func():


...
return Python
globals()
Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
...
and Enterprise Applications with Jython covers important topics such as:
>>> func()
{'func': <function func at 428fc>, 'gvar3': [3, 3, 3], 'gvar1': 1, 'gvar2': '
Fundamental programming concepts, including statements, expressions,
...
interpreters, and compilers

locals()

Python basics, including operators, string formatting, namespaces, classes, errors,


and exceptions
Thelocals() function is like globals() except that it returns the variables in the innermost namespace.
Object-oriented programming concepts

>>> def func2(var1, var2, var3):


...
return locals()
File input/output
...
>>> func2(1,2,3) Python's intrinsic functions
{'var2': 2, 'var3': 3, 'var1': 1}

Formatting, parsing, and manipulating strings


This shows the use of locals() in the body of func2 to print out the variables in func2's namespace.
Interfacing with the Java APIs and working with Java Streams
locals() also returns any variables defined inside the function.
Using Python and Java Swing to create GUIs

...
...
...
...

var4 = "more"
Working with SQL and JDBC(TM)
var5 = "five"
return locals()
Python and Java applets

In addition, the book contains instructions for downloading and installing the Python

>>> func3(1,2,3)
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
{'var2': 2, 'var3':
3, 'var1': 1, 'var4': 'more', 'var5': 'five'}
and numerous code samples make this book a useful learning experience.
Herevar4 and var5 are returned as well as the arguments passed to func3.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
vars()
give you insight into the power of Python and the know-how to put it to work.
Thevars() function is like locals() except that you can use it for any object type to list the object's
public attributes. Here we use vars() to list the attributes in the Exception class. (Exception is
alwayswell, almost alwaysin the namespace.)

777

Python Programming with the Java Class Libraries: A Tutorial for Building
>>> vars(Exception)
Web'exceptions',
and Enterprise Applications
with Jython
{'__module__':
'__init__':
<function __init__ at 27b8c>, '__doc
By Richard Hightower

Type Checking:
callable(),
type()
Publisher:
Addison Wesley
Pub Date: June 28, 2002

Thecallable(object)
function
returns true if the object can be called like a function. Since more
ISBN:
0-201-61616-5
Table types
of
thanobject
can be callable
(lambdas,
functions,
methods, class instances, etc.), this feature is very useful.
Pages: 640
Contents
Here's an example:
Characterized by ease of use, richness of expression, and concise syntax, Python has
>>> callable(dir)
remained a premier programming language for more than a decade, and is used by
1
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
This is nice, but how do you use it? Let's say that you want to find out which objects in the current module are
application development.
callable.

This tutorial begins with coverage of some of the basics of Python programming. Using
Define a class whose instances are callable.
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
>>> class myclass:
techniques. For experienced programmers, the book demonstrates Python's breadth of
...
def __call__(self):
capabilities
shows the ways that Python interfaces with Java APIs for professional
...
return and
"hello"
application development.
...
Programming
Define an instance ofPython
the callable
class. with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

>>> hello = myclass()


Fundamental programming concepts, including statements, expressions,
Define some not so useful functions.
interpreters, and compilers

>>>
...
>>>
...
>>>
...
>>>

def func():pass
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
def func1():pass
Object-oriented programming concepts
def func2():pass
File input/output

def func3():pass

Python's intrinsic functions


Iterate through the list of variables in the module namespace, and see which objects are callable.
Formatting, parsing, and manipulating strings

>>> for (name,value) in vars().items():


...
if (callable(value)):
Interfacing with the Java APIs and working with Java Streams
...
print name + " is callable"
...
Using Python and Java Swing to create GUIs
hello is callable
Working with SQL and JDBC(TM)
myclass is callable
func is callable
func1 is callablePython and Java applets
func2 is callable
In addition, the book contains instructions for downloading and installing the Python
func3 is callable

language and the Java Development Kit (JDK). Terminology, definitions, explanations,
andreturns
numerous
codeofsamples
make this book a useful learning experience.
Thetype() function
the type
the object.
Whether you are a sophisticated computer user new to programming or a serious
>>> type(myclass)
application developer, Python Programming
<jclass org.python.core.PyClass
. . .> with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

>>> type (func)


<jclass org.python.core.PyFunction . . .>

777

>>> type (dir())

<jclass org.python.core.PyList
. .Java
. >Class Libraries: A Tutorial for Building
Python Programming with the
Web and Enterprise Applications with Jython

>>> type(hello)
By Richard Hightower
<jclass org.python.core.PyInstance . . .>
Publisher: Addison Wesley

Operations

This

Table of
Contents
section
deals

Pub Date: June 28, 2002


ISBN: 0-201-61616-5
Pages: 640

mostly with functions that are longhand for operators.

Characterized by ease of use, richness of expression, and concise syntax, Python has

Numeric Operations:
divmod(),language
pow(),forabs(),
round()
remained a cmp(),
premier programming
more than
a decade, and is used by

novices and professionals alike. In particular, its close relationship to Java(TM) makes

cmp(x,y) compares
two languages,
numeric types.
It used
also works
for sequences,
other numeric
objects.
the two
when
in combination,
idealdictionaries,
for Web andand
distributed
enterprise
cmp() returns a positive
number
if the x argument is greater than the y argument, a negative number if the y
application
development.
argument is greater than the x argument, and 0 if x and y are equal.
This tutorial begins with coverage of some of the basics of Python programming. Using
>>> cmp(1,0) plenty of skill-building exercises and interactive programming sessions, this book will
1
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
>>> cmp(0,1) capabilities and shows the ways that Python interfaces with Java APIs for professional
-1
application development.

>>> cmp(0,0) Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
0
and Enterprise Applications with Jython covers important topics such as:
cmp() is related to the equality operators (==,>=,<=, etc.). If you want these operators to work with class
Fundamental
programming
including
statements, expressions,
instances, you need to implement
cmp()
for the classconcepts,
by executing
cmp(instance1,
instance2),
interpreters,
compilers > instance2).
instance1 == instance2
, orand
instance1
Python basics,
including
string formatting,
namespaces,
classes, errors,
Thedivmod() function divides
a by b and
returnsoperators,
a tuple containing
the divider
and the remainder.
With
and
exceptions
divmod() , these two examples are equivalent:
programming concepts
>>> 100 / 10, 100Object-oriented
% 10
(10, 0)
File input/output

>>> divmod(100,10)
Python's intrinsic functions
(10, 0)
Formatting, parsing, and manipulating strings
Thepow() function raises x to the power of y, so these two examples are the same:

>>> 5**3
125
>>> pow(5,3)
125

Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs
Working with SQL and JDBC(TM)

Python and Java applets


Theabs() function returns the absolute value of a number.
In addition, the book contains instructions for downloading and installing the Python
>>> abs(1), abs(-1)
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
(1, 1)
and numerous code samples make this book a useful learning experience.
Theround(x, [n])
function
rounds
a number with
a fraction
thetonearest
whole integer
(or, if you
Whether
you are
a sophisticated
computer
user to
new
programming
or a serious
specify the n argument,
to
the
nearest
position
in
the
mantissa).
Here's
an
example.
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.
Declare a variable containing a float with a long mantissa.

777

>>> myfloat = 1.1111111111111111


Round to the nearest whole integer.

Python Programming with the Java Class Libraries: A Tutorial for Building

>>> round(myfloat)
Web and Enterprise Applications with Jython
1.0
By Richard Hightower
Round to the second decimal place in the mantissa.
Publisher: Addison Wesley

Pub Date:
>>> round(myfloat,
2)June 28, 2002
ISBN: 0-201-61616-5
1.11

Table of
Contents

Pages: 640

Round to the third decimal place in the mantissa.


Characterized by ease of use, richness of expression, and concise syntax, Python has
>>> round(myfloat,
remained a3)
premier programming language for more than a decade, and is used by
1.111
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
Identity: hash(),
id() development.
application

This
tutorial
begins with
coverage ofthesome
Python
Using
Thehash() function
returns
a number
that represents
dataof
ofthe
an basics
object,of
called
the programming.
hash value. Hash
values
plenty
of
skill-building
exercises
and
interactive
programming
sessions,
this
book
will
are integers that can be used to efficiently compare dictionary keys.
help those new to programming develop an understanding of concepts and practical
>>> myint= 1 techniques. For experienced programmers, the book demonstrates Python's breadth of
and shows the ways that Python interfaces with Java APIs for professional
>>> myfloat =capabilities
1.0
application development.
>>> hash(myint)

1
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
>>> hash(myfloat)

1
Fundamental programming concepts, including statements, expressions,
Theid(object) function assigns objects in the system a unique ID. It implements the is operator. In the
interpreters, and compilers
following statements, id and is are functionally equivalent:
Python basics, including operators, string formatting, namespaces, classes, errors,

>>> dict = {}
and exceptions
>>> id(dict)==id(dict), dict is dict
(1, 1)
Object-oriented programming concepts

File Modules:
input/output delattr(), getattr(), hasattr(), setattr()
Class, Instance, and
Python's intrinsic
Thedelattr(object,name)
functionfunctions
removes attributes from a class or instance or removes variables
from a module namespace. It works similarly to del(). Consider the following example, which defines an
Formatting, parsing, and manipulating strings
empty class, myclass, creates an instance of it, and adds attributes to the instance.
Define myclass.

Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs

>>> class myclass:pass


...
Working with SQL and JDBC(TM)

Create an instance of myclass


instance"), and add to it the attributes "hello" and
Python,ci
and("class
Java applets
"goodbye".
In addition, the book contains instructions for downloading and installing the Python
>>> ci = myclass()
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.

>>> ci.hello = "hello"


>>> ci.goodbye
= "goodbye"
Whether
you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
Display the attributes.
give you insight into the power of Python and the know-how to put it to work.

>>> vars(ci)
{'goodbye': 'goodbye', 'hello': 'hello'}

777

Use the del keyword to delete the "hello" attribute: then display the attributes that remain.

Python Programming with the Java Class Libraries: A Tutorial for Building

>>> del ci.hello


Web and Enterprise Applications with Jython
>>> vars(ci) ByRichard Hightower
{'goodbye': 'goodbye'}

Publisher: Addison Wesley


Use delattr()to delete
"goodbye" from the class instance, and use vars() to show that the instance
has no more attributes. Pub Date: June 28, 2002
Table of

ISBN: 0-201-61616-5

Pages: 640
>>> Contents
delattr(ci,"goodbye")
>>> vars(ci)
Characterized by ease of use, richness of expression, and concise syntax, Python has
{}

remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in Del
combination, ideal for Web and distributed enterprise
application development.
You can't use delattr() to remove items (key/value pairs) from a dictionary; only the del
This tutorial begins with coverage of some of the basics of Python programming. Using
keyword can do that. del and delattr() are equivalent only for classes, instances, and
plenty of skill-building exercises and interactive programming sessions, this book will
modules.
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
Here's an example that
works with
module,
It justinterfaces
defines two
and attr2.
capabilities
anda shows
themymodule.py.
ways that Python
withvariables,
Java APIsattr1
for professional

attr1=1
attr2=2

application development.

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
Importmymodule.py into the interactive interpreter.

>>> import mymodule


Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
Showmymodule's namespace with the dir() function.
Python basics, including operators, string formatting, namespaces, classes, errors,

>>> dir (mymodule)


and exceptions
['__builtins__', '__doc__', '__file__', '__name__', 'attr1', 'attr2']
Object-oriented programming concepts
Use delattr() to remove attr1 from the namespace.
File input/output

>>> delattr(mymodule, "attr1")


Verify the removal.

Python's intrinsic functions


Formatting, parsing, and manipulating strings

>>> dir(mymodule)
['__builtins__', Interfacing
'__doc__',
'__name__',
'attr2']
with the'__file__',
Java APIs and working
with Java Streams
Use del() to do the sameUsing
thing Python
with attr2
. Swing to create GUIs
and Java

>>> del mymodule.attr2


Working with SQL and JDBC(TM)
>>> dir(mymodule)
['__builtins__', Python
'__doc__',
'__file__', '__name__']
and Java applets
Thegetattr() function,
strange
as it may
seem,instructions
"gets" an attribute
from a class,
In addition,
the book
contains
for downloading
and instance,
installingor
themodule.
Python Here's
an example using a class,
myclass2
, whose
instances Kit
have(JDK).
the attributes
namedefinitions,
and height
.
language
and the Java
Development
Terminology,
explanations,
and numerous code samples make this book a useful learning experience.
Define myclass2 .
Whether you are a sophisticated computer user new to programming or a serious
>>> class myclass2:
application developer, Python Programming with the Java(TM) Class Libraries will
...
def __init__(self):
give you insight into the power of Python and the know-how to put it to work.

...
self.name = "Bob"
...
self.height = "5'11"
...
>>> ci = myclass2()

777

Display the attributesPython


of the class
instance.
Programming

with the Java Class Libraries: A Tutorial for Building


Web and Enterprise Applications with Jython
vars(ci) ByRichard Hightower

>>>
{'height': "5'11", 'name': 'Bob'}
Publisher: Addison Wesley

Get the height attribute.

Pub Date: June 28, 2002

ISBN: 0-201-61616-5
>>> Table
getattr(ci,
"height")
of

Pages:
640
"5'11"
Contents

There's an easier wayCharacterized


to do this. by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
>>> ci.heightnovices and professionals alike. In particular, its close relationship to Java(TM) makes
"5'11"
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
But with getattr() we can get attributes dynamically at runtime.
This tutorial begins with coverage of some of the basics of Python programming. Using
Thegetattr() function
works withexercises
modules:and interactive programming sessions, this book will
plenty ofalso
skill-building
help those new to programming develop an understanding of concepts and practical
>>> getattr(mymodule,
"attr1")
techniques. For experienced programmers, the book demonstrates Python's breadth of
1
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
which is equivalent to

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
>>>mymodule.attr1
and Enterprise Applications with Jython covers important topics such as:
1
Thehasattr() function checks to see if a class, instance, or module has an attribute. It returns true if so,
Fundamental programming concepts, including statements, expressions,
false if not. Continuing ourinterpreters,
mymodule.py
we have the following:
andexample,
compilers

>>> hasattr(ci,"height")
Python basics, including operators, string formatting, namespaces, classes, errors,
1
and exceptions
>>> hasattr(ci,"weight")
Object-oriented programming concepts
0
File input/output

hasattr() also works with modules.


Python's intrinsic functions

>>> hasattr(mymodule, "attr1")


1
Formatting, parsing, and manipulating strings
Thesetattr() functionInterfacing
sets an attribute
forJava
a class,
or module.
Still Streams
with the same example, we'll
with the
APIsinstance,
and working
with Java
add the weight attribute to the class instance.
Using Python and Java Swing to create GUIs
Determine if the ci class instance already has weight.
Working with SQL and JDBC(TM)

>>> hasattr(ci,"weight")
Python and Java applets
0
In addition,
theadd
book
The0 (false) value indicates
no, so
it. contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
>>> setattr(ci,"weight",
220) make this book a useful learning experience.
and numerous code samples
Now does it have it?Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
>>> hasattr(ci,"weight")
give you insight into the power of Python and the know-how to put it to work.
The1 (true) value indicates yes.

777

We know the other way to add the weight attribute, but first we need to remove it.

>>> delattr(ci,
"weight")
#remove
itClass Libraries: A Tutorial for Building
Python
Programming with
the Java
>>> hasattr(ci,
"weight")
# make with
sure
it is gone
Web and
Enterprise Applications
Jython
0
By Richard Hightower
Now we set it and checkPublisher:
to see if it's
there. Wesley
Addison
Date: June 28, 2002
>>> ci.weight =Pub220
ISBN: 0-201-61616-5
>>> Table
hasattr(ci,"weight")
of
Pages: 640
1 Contents

Characterized by ease of use, richness of expression, and concise syntax, Python has
Working with Modules
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
Here's an example of how setattr(),hasattr(), and delattr() work with modules.
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
Import the sys module.
This tutorial begins with coverage of some of the basics of Python programming. Using
>>> import sys
plenty of skill-building exercises and interactive programming sessions, this book will
helpobjects.
those new to programming develop an understanding of concepts and practical
Get the exit and version
techniques. For experienced programmers, the book demonstrates Python's breadth of
>>> getattr(sys,
"exit")
capabilities
and shows the ways that Python interfaces with Java APIs for professional
<built-in function
applicationexit>
development.

Python Programming
with the Java(TM) Class Libraries: A Tutorial for Building Web
>>> getattr(sys,
"version")
and
Enterprise
Applications
JythonSH3]'
covers important topics such as:
'1.5.1 (#0, 07/16/98 22:30:00)with
[MSC
Remove the exit() function and make sure it's gone.
Fundamental programming concepts, including statements, expressions,
>>> delattr(sys, interpreters,
"exit")and compilers

>>> hasattr(sys, "exit")


Python basics, including operators, string formatting, namespaces, classes, errors,
0
and exceptions
Redefine the exit object in the context of the sys module.
Object-oriented programming concepts

>>> setattr(sys,"exit","exit has left the building")


File input/output
Display the new exit() function.
Python's intrinsic functions

>>> getattr(sys, "exit")


Formatting,
parsing, and manipulating strings
'exit has left the
building'
Interfacing with the Java APIs and working with Java Streams

cmp() and Classes and Dictionaries

Using Python and Java Swing to create GUIs

cmp() works with many object types. For example, if left undefined, it works with class instances just as id or
with SQL
and JDBC(TM)
is does. As with numeric Working
objects, cmp()
returns
0 if the objects are equal. Here's an illustration.
Create two class instances.Python and Java applets

the book contains instructions for downloading and installing the Python
>>> ci1,ci2 =In addition,
myclass2(),myclass2()
Compare them.

language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.

Whether you are a sophisticated computer user new to programming or a serious


>>> cmp(ci1,ci2)
application developer, Python Programming with the Java(TM) Class Libraries will
-1
give you insight into the power of Python and the know-how to put it to work.
Even though the values are the same, the instances are unequal because the default is to check object identity (to
make sure that the variable references the same object).

777

Compare one instance to itself.

>>> cmp(ci1,ci1)
Python Programming with the Java Class Libraries: A Tutorial for Building
0
Web and Enterprise Applications with Jython
By Richard Hightower

Sincecmp() checks identity for equality, comparing an object to itself returns 0, which means equality.
Publisher: Addison Wesley

Thecmp() method defines the behavior of the equality operators. That means that the following is like using
Pub Date: June 28, 2002
the identity operator:

>>>
0

Table of
ci1 ==
Contents

ISBN: 0-201-61616-5

ci2

Pages: 640

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
>>> ci1 == ci1
novices and professionals alike. In particular, its close relationship to Java(TM) makes
1
the two languages, when used in combination, ideal for Web and distributed enterprise
application
>>> ci1 is ci2,
ci1 development.
is ci1

(0, 1)

This tutorial begins with coverage of some of the basics of Python programming. Using
plentyof
of __
skill-building
exercises
interactiveclass.
programming
Chapter 8 has an example
cmp__ defined
for theand
Address
Here's an sessions,
excerpt: this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
def __cmp__(self,other):
capabilities and shows the ways that Python interfaces with Java APIs for professional
"""
application
development.instance to another.
Compares
one address

If the address instances are equal the __cmp__ returns 0.


Python
Programmingare
with the
Java(TM)
Libraries:
A Tutorial afornon-zero
Building Web
If the address
instances
not
equalClass
then
we return
and
Enterprise
Applications
with
Jython
covers
important
topics
such
as:
value.
"""
# To programming
implementconcepts,
this including
all westatements,
do is expressions,
compare
Fundamental
# the dictionaries
of
the
class
interpreters, and compilers
# The __dict__ member of the instance holds
# all of the instance
fields
Python basics,
including operators, string formatting, namespaces, classes, errors,
# in a dictionaryand exceptions
return cmp(self.__dict__ ,other.__dict__)
Object-oriented programming concepts
This compares all attribute values of one instance of Address with those of another instance. Remember, the
File input/output
default is just to compare identity.
Python's intrinsic functions
Sequence and Collection:
len(), max(), min(), cmp()
Formatting, parsing, and manipulating strings
We covered sequences and collections in Chapter 1, so we'll just review them here.
Interfacing with the Java APIs and working with Java Streams
Thelen(s) method returns the length of a sequence or dictionary. It works with tuples, lists, and dictionaries,
as shown in the following three
Usingexamples:
Python and Java Swing to create GUIs

>>> len((1,2,3)) Working with SQL and JDBC(TM)


3
Python and Java applets

>>> len([1,2,3])
In addition, the book contains instructions for downloading and installing the Python
3
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code
>>> len({1:1,2:2,3:3}
) samples make this book a useful learning experience.

Whether you are a sophisticated computer user new to programming or a serious


application
developer,
Python
Programming
with
the Java(TM)
Classwhich
Libraries
Themax(s) function
returns the
max value
in a sequence.
It uses
cmp()
to determine
itemwill
in the list
give
you
insight
into
the
power
of
Python
and
the
know-how
to
put
it
to
work.
is the greatest.

>>> max((1,2,3))
3

777

Themin(s) function
returns
the min valuewith
in the
list.Java
Python
Programming
the

>>>
1

Class Libraries: A Tutorial for Building


Web and Enterprise Applications with Jython
min((1,2,3))
By Richard Hightower
Publisher: Addison Wesley

Thecmp(x,y) method compares sequences (list and tuple) to sequences and dictionaries to dictionaries.
Pub Date: June 28, 2002
Here's how.
Table of
three tuples,
Create
Contents

ISBN: 0-201-61616-5

640 having
the firstPages:
and second

equal values.

>>> list1,list2,list3=(1,2,3),(1,2,3),(1,2,4)
Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
Compare the first and
the second
tuples.
novices
and professionals
alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
>>> cmp (list1,
list2)
#cmp returns 0 if they are equal
application
development.

This tutorial begins with coverage of some of the basics of Python programming. Using

>>> list1==list2
plenty of skill-building exercises and interactive programming sessions, this book will
1
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
Compare the secondcapabilities
and third tuples.
and shows the ways that Python interfaces with Java APIs for professional
application development.

>>> cmp(list2, list3)


-1
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

>>> cmp(list3, list2)


1

Fundamental programming concepts, including statements, expressions,


>>> list2==list3 interpreters, and compilers

0
Create two dictionaries.

Python basics, including operators, string formatting, namespaces, classes, errors,


and exceptions

>>> dict1,dict2 =Object-oriented


{1:1,2:2,3:3}
, {1:1,2:2,3:3}
programming
concepts
Compare them.

File input/output

1
Python's intrinsic functions
>>> cmp (dict1, dict2) #cmp returns 0 if they are equal
Formatting, parsing, and manipulating strings
0
Interfacing with the Java APIs and working with Java Streams
Add an item to the first dictionary.
Using Python and Java Swing to create GUIs
>>> dict1["cow"]="moo"
Working
with SQL
and JDBC(TM)
Compare the first and second
dictionaries
again.

>>> dict1==dict2 Python and Java applets


0

In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
>>> cmp(dict1,dict2)
and numerous code samples make this book a useful learning experience.
1
Whether you are a sophisticated computer user new to programming or a serious

Modules: reload()
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.
Thereload() function allows you to dynamically reload a module. It comes in very handy when you're
debugging code. Here's an example with the string module:

777

>>> import string

>>> reload(string)
Python Programming with the Java Class Libraries: A Tutorial for Building
<module 'string'>
Web and Enterprise Applications with Jython
By Richard Hightower

During development of a module, it's often necessary to make minor changes. Instead of exiting the interactive
interpreter, you can make
your changes
andWesley
then reload.
Publisher:
Addison
Pub Date: June 28, 2002
reload() needs a reference
to the module. Let's say you're using the from <module> import
ISBN: 0-201-61616-5
<object>
form
of
the
import
statement. In that case, you don't have a reference to the module, even
Table of

Pages: 640
thoughContents
the module is loaded.
(You need to exit and restart the interactive interpreter for this example.)

Characterized
of use, richness of expression, and concise syntax, Python has
>>> from string
importby ease
find
remained
a
premier
programming
language for more than a decade, and is used by
>>> print find
novices
and
professionals
alike.
In
particular, its close relationship to Java(TM) makes
<built-in function find>
the
two
languages,
when
used
in
combination,
ideal for Web and distributed enterprise
>>> print string
application
development.
Traceback (innermost last):
File "<interactive input>", line 1, in ?
This tutorial begins with coverage of some of the basics of Python programming. Using
NameError: string

plenty of skill-building exercises and interactive programming sessions, this book will
help those
to programming
develop
an understanding
concepts
and so
practical
Although we have access
to thenew
find()
function, we
don't have
access to theofstring
module,
when we try to
techniques.
For
experienced
programmers,
the
book
demonstrates
Python's
print it out we get a NameError. To reload find() we have to first import and reload stringbreadth
(whichofputs it
capabilities
showswith
the ways
that Python interfaces with Java APIs for professional
in the current namespace).
We'lland
continue
our example.
application development.
Explicitly import string.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
>>> import string
and Enterprise Applications with Jython covers important topics such as:
Reload it.

Fundamental programming concepts, including statements, expressions,


>>> reload (string)
interpreters, and compilers

<module 'string'>
Python basics, including operators, string formatting, namespaces, classes, errors,
Accessfind()as before. and exceptions

>>> del string #optionally


remove string
Object-oriented programming
concepts from your namespace
>>> print find
File input/output
<built-in function
find>
Python's
intrinsic
functions
Reloading the string module
will reload
all of
its code; any changes will be reflected at that time. This is a great
tool for debugging your Python modules.
Formatting, parsing, and manipulating strings
The__import__() function (__import__(name, [globals], [locals],
Interfacing
with the
Java APIs
and working
with Java
Streams
[fromlist])) works like
the import
statement,
except
that it allows
you to
pass the name of the module
as a string. Imagine a program that, given a command-line argument, loads a module and executes its test()
Using Python and Java Swing to create GUIs
function. You can use this test harness with many different modules with many different names. Now imagine
another program that detects
how it connects
theJDBC(TM)
home office and, based on that information, loads the correct
Working
with SQLtoand
module to talk to the boss.
Python and Java applets
Here's an example of __import__():
In addition, the book contains instructions for downloading and installing the Python
>>> __import__("string")
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
<module 'string'>
and numerous code samples make this book a useful learning experience.
Whether
you are a sophisticated
computer user new to programming or a serious
Class Operations:
isinstance(),
issubclass()
application developer, Python Programming with the Java(TM) Class Libraries will
giveisinstance()
you insight into the and
power
of Python and thefunctions
know-how
put it to
We covered the built-in
issubclass()
in to
Chapter
6, work.
but let's briefly
review them. We're going to use the following code, which defines a class hierarchy:

777

>>> class animal:


...
pass

...

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
mammal(animal):
By Richard Hightower

>>> class
...
pass
...

Publisher: Addison Wesley


Pub Date: June 28, 2002

>>> class human(mammal):


ISBN: 0-201-61616-5
of
... Table
pass
Pages: 640
... Contents
Characterized by ease of use, richness of expression, and concise syntax, Python has

>>> class geek:


remained a premier programming language for more than a decade, and is used by
...
pass novices and professionals alike. In particular, its close relationship to Java(TM) makes
...
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.

>>> class programmer(geek, human):


...
pass This tutorial begins with coverage of some of the basics of Python programming. Using
...
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
Theisinstance(object,class)
function
determinesthe
if the
instance
is of a particular
class. It of
works
techniques. For experienced
programmers,
book
demonstrates
Python's breadth
with the instance's base
class; that
is,shows
if the human
class
a subclass
of the with
mammal
anyprofessional
instance of
capabilities
and
the ways
thatisPython
interfaces
Java class,
APIs for
human is also an instance
of
mammal.
For
example:
application development.

>>> Rick = programmer()


Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
Is the Rick class instance an instance of programmer?

>>> isinstance(Rick,programmer)
Fundamental programming concepts, including statements, expressions,
1
interpreters, and compilers
Is Rick a geek?

Python basics, including operators, string formatting, namespaces, classes, errors,


and exceptions

>>> isinstance(Rick,geek)
1
Object-oriented programming concepts
Are programmers human? File input/output

>>> isinstance(Rick,human)
Python's intrinsic functions
1
Formatting, parsing, and manipulating strings
SinceRick is an instance of programmer and programmer is a subclass of human,Rick is an
instance of human.
Interfacing with the Java APIs and working with Java Streams
Of course, it doesn't stop with
thePython
immediate
base Swing
classes.toRick
an instance of mammal and animal
Using
and Java
createisGUIs
because these are in the base class hierarchy of programmer.
Working with SQL and JDBC(TM)
Is Rick a mammal?
Python and Java applets

>>> isinstance(Rick, mammal)


In addition, the book contains instructions for downloading and installing the Python
1
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
Is Rick an animal? and numerous code samples make this book a useful learning experience.

>>> isinstance(Rick,
animal)
Whether you are
a sophisticated computer user new to programming or a serious
1
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.
Since Rick is a human and humans are subclasses of mammals, Rick is a mammal. Since Rick is a mammal and
mammals are subclasses of animals, Rick is an animal.

777

issubclass(class1, class2) returns whether one class is a subclass of another. Our illustration of

issubclass() Python
will continue
our class hierarchy.
Programming
with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython

Ishuman a subclassBy
ofRichard
animal
?
Hightower

>>> issubclass(human, animal)


Publisher: Addison Wesley
1
Pub Date: June 28, 2002

ISBN: ?0-201-61616-5
Ishuman
a subclass of mammal
Table of

Pages: 640

Contents

>>> issubclass(human, mammal)


1
Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
Isgeek a subclass of
animal
novices
and?professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
>>> issubclass(geek,animal)
application development.

This tutorial begins with coverage of some of the basics of Python programming. Using

issubclass() plenty
doesn'tofwork
just for immediate
but for
subclasses anywhere
thebook
hierarchy
skill-building
exercisessubclasses
and interactive
programming
sessions, in
this
will that
have a class as a basehelp
class
anywhere
their own hierarchy.
those
new toinprogramming
develop an understanding of concepts and practical

techniques. For experienced programmers, the book demonstrates Python's breadth of

I/O: open(), raw_input()


capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
Theopen(filename, [mode], [bufsize]) function returns a file object. Again, this is just a
Programming
with7.the Java(TM) Class Libraries: A Tutorial for Building Web
brief review since wePython
covered
I/O in Chapter
and Enterprise Applications with Jython covers important topics such as:
Open a file for reading.
Fundamental programming concepts,
>>> file = open("\\dat\\exp.txt",
"w") including statements, expressions,
interpreters, and compilers
>>> file.write("Hello")
>>> file.close()
Open a file for writing.

Python basics, including operators, string formatting, namespaces, classes, errors,


and exceptions

Object-oriented programming concepts


>>> file = open("\\dat\\exp.txt")
>>> file.read()
File input/output
'Hello'
Python's
intrinsic
functions
Themode argument specifies
read ("r"
), write
("w"), read/write ("r+"), and append ("a") mode.
bufsize sets the size ofFormatting,
the buffer. Setting the buffer to zero means no buffering. (For more on buffering see
parsing, and manipulating strings
Chapter 12.)
Interfacing with the Java APIs and working with Java Streams
Theraw_input([prompt]) function reads input from the user. The prompt tells the user what that input
should be and returns it when
the Python
user hits
Enter.
following
this:
Using
and
JavaTry
Swing
to create
GUIs

>>> raw_input("Enter
age:
")
Workingyour
with SQL
and JDBC(TM)
Enter your age: 31
'31'
Python and Java applets
In addition, the book contains instructions for downloading and installing the Python

Advanced Topic:
Functional
Programming
language and
the Java Development
Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
You don't need to know functional programming to develop Python code, but learning it can reduce the amount
of code you write. Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
you insight
into the power of Python and the know-how to put it to work.
apply(), filter(),give
map(),
reduce

777

Theapply(function, args, [keywords]) function needs a callable object as the function


argument, which it calls with args as the argument list (and keywords as the named argument list). args
is a sequence, keywords a dictionary.

The function

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

>>> def hello(str):


...
print "hello " + str
Publisher: Addison Wesley
...
Pub Date: June 28, 2002
ISBN:
can be called with apply()
like0-201-61616-5
this:

Table of
Contents

Pages: 640

>>> apply(hello,("Bobby",))
hello Bobby Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
Withoutapply() it's
calledand
likeprofessionals
this.
novices
alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise

>>> hello("Bobby")
application development.
hello Bobby

This tutorial begins with coverage of some of the basics of Python programming. Using
You can use apply()to call several functions. Or you can have several functions operating on the same data.
plenty of skill-building exercises and interactive programming sessions, this book will
help those new
to programming
develop
an understanding
of concepts
practical
Thefilter(function,
list)
function filters
out items
in a list. Its argument
is a and
callable
object that
techniques. For experienced programmers, the book demonstrates Python's breadth of
takes an item out of the list and returns true or false. Let's say the only list items we want are those that begin
capabilities and shows the ways that Python interfaces with Java APIs for professional
withR.
application development.
Create a list containing names.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise
Applications
with Jython
covers important
topics such as:
>>> list = ["Mary",
"Adam",
"Bob",
"Rick",
"Robert"]
Define a function that returns true if the name starts with R.
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
>>> def Rfilter(name):

...
...
...

if name[0]=="R": return 1
Python basics,
including0operators, string formatting, namespaces, classes, errors,
else:
return
and exceptions

Object-oriented
programming
Invokefilter() , passing
it the Rfilter
and listconcepts
arguments.
File input/output
>>> filter(Rfilter,list)
['Rick', 'Robert']
Python's intrinsic functions
This example is, admittedly,
contrived. parsing,
In a realand
situation,
the items
in the sequence can be much more complex
Formatting,
manipulating
strings
than just strings; they can be class instances or dictionaries with 100 items, or tuples with dictionaries, class
instances, and lists. Also, the
function with
passed
beAPIs
just short
of rocketwith
science.
point is that filter()
Interfacing
thecan
Java
and working
Java The
Streams
returns every item in the list where the item applied to it returns a true value.
Using Python and Java Swing to create GUIs
As an exercise, rewrite the above functionality with for loops instead of filter() . Which code is more
concise? Which code is easier
to understand?
you answer these questions, I think you'll find that
Working
with SQLOnce
and JDBC(TM)
filter() is very useful.
Python and Java applets
Themap(function, list) function is similar to filter() . It applies functions to every item in a list
In for
addition,
the book(item)
contains
for downloading
installing
Python
and returns the results
each function
call.instructions
map()'s first
argument is a and
callable
type; the
its second
argument is a list. language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
As an example, let's say you have the following sequence that you want to convert into a string:
Whether you are a sophisticated computer user new to programming or a serious
>>> seq = (72,
105, developer,
32, 77,Python
111,
109)
application
Programming
with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.
which you can do with a for loop.

777

>>> list = []
>>> for item in seq:

...
list.append(chr(item))
Python Programming with the Java Class Libraries: A Tutorial for Building
...
Web and Enterprise Applications with Jython
>>> from string
import
join
By Richard
Hightower
>>> str = join(list,"")
Publisher: Addison Wesley

After this code executes, str will contain a string version of the sequence, and it will take only four lines (we
Pub Date: June 28, 2002
won't count from stringimport join). With the map() function, you can do all four lines of code
ISBN: 0-201-61616-5
Table
of call.
in one
method

Contents

Pages: 640

>>> str = join(map(chr,seq),"")

Characterized by ease of use, richness of expression, and concise syntax, Python has
remainedisainside
premier
language
Note that the call to map()
theprogramming
join() function
call.for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
You may be wondering
whatlanguages,
str contains.
unravel
this mystery,
enter
the code
example. enterprise
the two
whenTo
used
in combination,
ideal
forinWeb
and distributed
application development.

>>> str
This tutorial begins with coverage of some of the basics of Python programming. Using
Thereduce(function,
list, [initializer])
function
is very similar
to filter()
plenty of skill-building
exercises and interactive
programming
sessions,
this book willand
map() in that a function
parameter
applied to each
item inana understanding
sequence. However,
insteadand
of practical
returning a list it
help those
new toisprogramming
develop
of concepts
returns one value. techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
Let's say that you want
to sum updevelopment.
the following list (the list variable is really a tuple):
application

>>> list = (1,2,3,4,5,6,7,8,9,10)


Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
To do so with a for loop, you need to do something like this:

>>> sum=0
Fundamental programming concepts, including statements, expressions,
>>> for num in list:
interpreters, and compilers
...
sum = sum + num
>>> sum
Python basics, including operators, string formatting, namespaces, classes, errors,
55
and exceptions
Withreduce() , you do Object-oriented
something like this:
programming concepts

>>> def add(a,b):Filereturn


a + b
input/output
...
>>> reduce (add,list)
Python's intrinsic functions
55
Formatting, parsing, and manipulating strings
which cuts out two lines of code.
Interfacing with the Java APIs and working with Java Streams
If you want to cut out a third line, you can rewrite the above with a lambda function, which turns four lines into
Using Python and Java Swing to create GUIs
one (how very Pythonesque).
SQL and JDBC(TM)
>>> reduce(lambdaWorking
a,b: with
a+b,list)
55

Python and Java applets


Lambdas are a new concept. Think of them as anonymous functions but without names or parentheses. If you
In addition,
book contains
downloading and installing the Python
want to know more about
lambdathe
functions,
consultinstructions
the Pythonfor
documentation.
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
andelegant,
numerous
code samples
make this,map()
book a ,useful
learning experience.
Although powerful and
reduce()
,apply()
and filter()
(and, for that matter,
lambdas) can be confusing. Don't let them trip you up, thoughyou don't need to master them to program in
Whether you are a sophisticated computer user new to programming or a serious
Python.
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

Advanced exec and eval

777

Imagine easily sending code to update changes to a program or easily moving code around the network to update
remote clients. How about adding scriptability so that end users can write scripts to automate common tasks? In

other languages, these


thingsProgramming
are hard to accomplish.
PythonClass
they're
built intoAthe
language.
Python
with theInJava
Libraries:
Tutorial
for Building

compile()

Web and Enterprise Applications with Jython


By Richard Hightower

Publisher:
Addison Wesley
Thecompile(string,
filename,
kind) function converts a string into a code object that
Pub Date:
June 28, 2002
represents Python bytecode.
The filename
argument states the origin of the code, that is, the file name; the
ISBN:
kindTable
argument specifies how
the0-201-61616-5
code should be compiled based on the contents of the string argument.
of
are three choices for Pages:
There
kind:640
Contents

Characterized by ease of use, richness of expression, and concise syntax, Python has

exec a group
of statements
remained
a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes

eval a single
expression
the two languages, when used in combination, ideal for Web and distributed enterprise
application
development.
single a single
statement
tutorial begins
with
of some of
the basics
of to
Python
programming.
Using
compile() worksThis
in conjunction
with
thecoverage
eval statement,
which
you use
execute
the code object.
More
plenty
of
skill-building
exercises
and
interactive
programming
sessions,
this
book
willto
than likely you'll use it to execute a string representing code over and over again so that eval won't have
help those new to programming develop an understanding of concepts and practical
execute the string by recompiling the code object each time.
techniques. For experienced programmers, the book demonstrates Python's breadth of
and shows
theexec
ways kind
that Python
interfaces
with Java
professional
Here's an example ofcapabilities
compile()
with the
argument.
It pretends
that APIs
it hasfor
read
the string from
application development.
a file called friends.py.

>>> string = Python


""" Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and
Enterprise Applications with Jython covers important topics such as:
... friends = ['Ross','Rachel','Chandler','Joey','Tom','Jerry','Monica']
... for myfriend in friends:
...
print "Hello
" + myfriend
Fundamental programming concepts, including statements, expressions,
... """
interpreters, and compilers
>>> code = compile(string,"Friends.py","exec")
>>> eval(code) Python basics, including operators, string formatting, namespaces, classes, errors,
Hello Ross
and exceptions
Hello Rachel
Hello Chandler Object-oriented programming concepts
Hello Joey
File input/output
Hello Tom
Hello Jerry
Python's intrinsic functions
Hello Monica
>>>
Formatting, parsing, and manipulating strings

Here's an example compiling an expression that returns a dictionary:


Interfacing with the Java APIs and working with Java Streams

>>>
>>>
>>>
{4:

str = "{1:1,2:2,3:3,4:4} "


Using Python and Java Swing to create GUIs
cd = compile (str,"string","eval")
eval(cd)
Working with SQL and JDBC(TM)
4, 3: 3, 2: 2, 1: 1}
Python and Java applets

>>> dict = eval(cd)


>>> type (dict)
In addition, the book contains instructions for downloading and installing the Python
<jclass org.python.core.PyDictionary
6190231>
language and the Java Development Kit at
(JDK).
Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
which compiles a single statement:
Whether you are a sophisticated computer user new to programming or a serious
>>> cd2 = compile("""print
"Hello
World"with
""",
"string",
"single")
application developer, Python
Programming
the Java(TM)
Class Libraries
will
>>> eval (cd2)
give you insight into the power of Python and the know-how to put it to work.

Hello World

777

Of course, we've covered eval(expressions, [globals], [locals]) quite a few times. Here
we'll drill down to the details that can make you stumble.

Python Programming with the Java Class Libraries: A Tutorial for Building
globals and locals
Web and Enterprise Applications with Jython
By Richard Hightower

eval'sglobals and locals arguments are dictionaries that contain the global variables, where the keys
are the variable names and the values are the objects to which the variables refer. Not specifying globals or
locals is the same asPublisher:
doing this:Addison Wesley
Pub Date: June 28, 2002

ISBN: 0-201-61616-5
eval(str,
globals(),
locals())
Table of

Contents

Pages: 640

which passes the variables from the current namespace.


Characterized by ease of use, richness of expression, and concise syntax, Python has
Here's an example ofremained
calling ana premier
eval statement:
programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
>>> a = 1
the two languages, when used in combination, ideal for Web and distributed enterprise
>>> eval("a")application development.

This tutorial begins with coverage of some of the basics of Python programming. Using
Since the a variable is in the global namespace, and we're not passing a dictionary for the global variables, it's
plenty of skill-building exercises and interactive programming sessions, this book will
the one used.
help those new to programming develop an understanding of concepts and practical
techniques.
Fora experienced
theargument.
book demonstrates
Python's
breadth
In this next call to eval
, we pass
dictionary forprogrammers,
the globals
You can see
that the
value of
of a in
capabilities
and
shows
the
ways
that
Python
interfaces
with
Java
APIs
for
professional
the dictionary overrides the value of a in the global area of the module.
application development.

>>> eval("a", {"a":2} )


Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
2

and Enterprise Applications with Jython covers important topics such as:
Here we pass a variable named a in the locals dictionary. The inner namespacelocalsoverrides the
value of the a global dictionary.
Fundamental programming concepts, including statements, expressions,
interpreters,
and compilers
>>> eval("a",{"a":2}
, {"a":3}
)

Python basics, including operators, string formatting, namespaces, classes, errors,


and we
exceptions
Continuing this example, here
use a local a (that is, local to the func() function). You can see that the a
in the local area takes precedence over the a in the global area (where we set a to 1).
Object-oriented programming concepts

>>> def func(): File input/output


...
a=4
...
print eval("a")
Python's intrinsic functions
...
>>> func()
Formatting, parsing, and manipulating strings
4
Interfacing with the Java APIs and working with Java Streams

execfile()

Using Python and Java Swing to create GUIs

Theexecfile(file,Working
[globals],
with SQL [locals])
and JDBC(TM)function acts just like the exec statement, except
that it reads the contents of a file and executes it. As with eval, you can specify globals and locals
and Java
arguments. Execfile()Python
may seem
a lot applets
like import() , but the code executed with it acts as if it were
executed in the current namespace. There is no namespace management with execfile as when a module is
In addition, the book contains instructions for downloading and installing the Python
imported.
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
numerous
code
samples world'
make this from
book a string.
useful learning experience.
Here's an example ofand
exec
printing
'hello

Whether
you are aworld'"
sophisticated computer user new to programming or a serious
>>> exec "print
'hello
hello world application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.
As an exercise, create a text file containing Python code that prints 'hello world' to the console. Then, in
the interactive interpreter, read and execute the file with execfile().

Summary

777

Python Programming with the Java Class Libraries: A Tutorial for Building
and
Enterprise
Applications
Of all of the chaptersWeb
so far,
this
one was the
most fun to with
write,Jython
simply because Python's numerous built-in
By Richard
Hightower
functions make simple
things even
simpler and impossible things possible. We reviewed a lot from other
chapters, but we also covered many new items, such as functional programming and executing scripts.
Publisher: Addison Wesley
Pub Date: June 28, 2002 CONTENTS

Table of
Contents

ISBN: 0-201-61616-5
Pages: 640

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
Object-oriented programming concepts
File input/output
Python's intrinsic functions
Formatting, parsing, and manipulating strings
Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs
Working with SQL and JDBC(TM)
Python and Java applets
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
CONTENTS
Web and Enterprise Applications with Jython
By Richard Hightower

Chapter 10. Working


with Strings
Publisher: Addison Wesley
Pub Date: June 28, 2002

Conversion: atoi(),
atof(),
atol()
ISBN:
0-201-61616-5
Table of
Case Change: capitalize(),
Pages: 640 capwords(), swapcases(), lower(), upper()
Contents
Finding: find(), rfind(), index(), rindex(), count(), replace()
Characterized
by easesplitfields(),
of use, richness
of expression,
and concise syntax, Python has
Splitting and
Joining: split(),
join(),
joinfields()
remained a premier programming language for more than a decade, and is used by
Stripping and Parsing: lstrip(), rstrip(), strip()
novices and professionals alike. In particular, its close relationship to Java(TM) makes
Adjusting Text:
ljust(),
rjust(),
center(),
zfill(), expandtabs()
the two
languages,
when
used in combination,
ideal for Web and distributed enterprise
Summary application development.

Terms in This Chapter


This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
Argument
Octal 8
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities
interfaces with Java APIs for professional
Decimal 10 and shows the ways that PythonParsing
application development.
Exception
Separator
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and
important topics such as:
FieldEnterprise Applications with Jython covers
Sequence
Function
string m odule
Fundamental programming concepts, including statements, expressions,
interpreters,
Hexadecimal
16 and compilers
Substring

Python basics, including operators, string


formatting, namespaces, classes, errors,
Namespace
Whitespace
and exceptions
Sooner or later, you'll need to format, parse, or manipulate strings. For these tasks, you'll likely use the functions
Object-oriented
programming
concepts
in the Python string module.
Spend some time
familiarizing
yourself with this module by following along with
the examples in this chapter.
File input/output

Conversion: atoi(),
atof(),
Python's
intrinsic atol()
functions
Formatting,
manipulating
strings
atoi(s[,base]) converts
a stringparsing,
into anand
integer.
The default
is decimal, but you can specify octal 8,
hexadecimal 16, or decimal 10. If 0 is the base, the string will be parsed as a hexadecimal if it has a leading 0x
Interfacing with the Java APIs and working with Java Streams
and as an octal if it has a leading 0. Otherwise, it will be treated as a decimal.

Using Python and Java Swing to create GUIs


Let's do an example. In this and all other examples in this chapter, you have to first import the string module:

from string import


*. with SQL and JDBC(TM)
Working
Convert"1" to an integer. Python and Java applets

>>> atoi("1")In addition, the book contains instructions for downloading and installing the Python
1
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Convert"255" to a base 10 integer.
Whether you are a sophisticated computer user new to programming or a serious

>>> atoi("255",10)
application developer, Python Programming with the Java(TM) Class Libraries will
255
give you insight into the power of Python and the know-how to put it to work.

Convert"FF" to a base 16 integer.

777

>>> atoi("FF",16)
255

Python
Programming
Theatof(s) function
converts
a string to awith
float.the Java

>>>
1.1

Class Libraries: A Tutorial for Building


Web and Enterprise Applications with Jython
By Richard Hightower
atof("1.1")
Publisher: Addison Wesley

Theatol(s[, base])
converts
string
to a long.
Pub Date:
Junea 28,
2002
of
>>> Table
atol("1")
1L Contents

ISBN: 0-201-61616-5
Pages: 640

Characterized by ease of use, richness of expression, and concise syntax, Python has

>>> atol("255",
16)a premier programming language for more than a decade, and is used by
remained
0xFFL
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application
development. capwords(), swapcases(), lower(),
Change:
capitalize(),

Case
upper()

This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those function
new to programming
develop
an understanding
of concepts and practical
Thecapitalize(word)
capitalizes a given
word
in a string.
techniques. For experienced programmers, the book demonstrates Python's breadth of
>>> capitalize("bill")
capabilities and shows the ways that Python interfaces with Java APIs for professional
'Bill'
application development.
Thecapwords(s)
function
capitalizes with
all words
in a string.
Python
Programming
the Java(TM)
Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

>>> str = "bill joy"


>>> str = capwords(str)
Fundamental programming concepts, including statements, expressions,
>>> print str
interpreters, and compilers
Bill Joy

Pythonconverts
basics, including
string formatting,
namespaces,
Theswapcases(s) function
uppercaseoperators,
letters to lowercase
letters and
vice versa.classes, errors,
and exceptions

>>> swapcase("ABC abc 123")


Object-oriented programming concepts
'abc ABC 123'
Fileofinput/output
(Frankly, I don't see the value
this one.)
Python's intrinsic
functions
Thelower(s) function converts
uppercase
letters to lowercase letters.
Formatting,
>>> lower("ABC abc
123")parsing, and manipulating strings
'abc abc 123'
Interfacing with the Java APIs and working with Java Streams
Theupper(s) function converts lowercase letters to uppercase letters.
Using Python and Java Swing to create GUIs

>>> upper("ABC abc 123")


Working with SQL and JDBC(TM)
'ABC ABC 123'
Python and Java applets

Finding: find(), rfind(), index(), rindex(), count(), replace()


In addition, the book contains instructions for downloading and installing the Python
language
and the
Java locate
Development
Kit (JDK).
definitions,
explanations,
The finding functions
in the string
module
a substring
within aTerminology,
string. For example,
substrings
of "Python
and
numerous
code
samples
make
this
book
a
useful
learning
experience.
is fun" are "Pyt", "is", "fun", "n is f", and so forth. Using a substring helps in parsing string data.
Whether
you are a sophisticated
computer
newposition
to programming
or a serious
Thefind(s, sub,
[start],[end])
function
finds user
the first
of a substring
in a given string.
application
developer,
Python
Programming
with
the
Java(TM)
Class
You can set the start and stop position arguments, which determine where in the string the Libraries
search willwill
begin and
give you insight into the power of Python and the know-how to put it to work.
end. Here's an example:

>>> str = "apple peach pear grapes apple lime lemon"


>>> position = find(str, "pear")

777

Here's a real-world use


of find()
: extracting
text
outJava
of a tag
whenLibraries:
reading inAan
HTML for
file Building
from a server.
Python
Programming
with
the
Class
Tutorial
Web and Enterprise Applications with Jython

Create some sample By


text
embedded
in HTML tags.
Richard
Hightower

>>>
#simulated input string from some file
Publisher: Addison Wesley
>>> str = "<h1> text we want to extract </h1>"
Pub Date: June 28, 2002

ISBN: 0-201-61616-5
Set theTable
start
and stop strings
(the HTML tags).
of

Contents

Pages: 640

>>> start = "<h1>"


#html tag
>>> stop = "</h1>"
#html
tag and concise syntax, Python has
Characterized by ease of use, richness
of expression,
remained a premier programming language for more than a decade, and is used by
Find the position of novices
the first and professionals
second strings.alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
>>> begin = find(str,start)
#find the location of the 1st tag
application development.

>>> end = find(str,stop)

#find the location of the 2nd tag

This tutorial begins with coverage of some of the basics of Python programming. Using
Locate the text to beplenty
extracted.
of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical

>>>
#compute where the start of the string we want is:
techniques. For experienced programmers, the book demonstrates Python's breadth of
>>> begin = begin + len(start)

capabilities and shows the ways that Python interfaces with Java APIs for professional
application
Extract the text embedded
in thedevelopment.
HTML tags, and display it.
Programming
with the
Java(TM)the
Class text
Libraries:
A Tutorial
Building Web
>>>
#usingPython
slice
notation
extract
from
the for
string
and
Enterprise
Applications
with
Jython
covers
important
topics
such
as:
>>> text = str[begin:end]
>>> print text
text we want to extract
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
The HTML tags supply the boundaries of the desired text.
Python basics, including operators, string formatting, namespaces, classes, errors,

rfind(s, sub, [start],[end]) is similar to find(), but it searches the substring from right to
and exceptions
left. Here it finds the last occurrence of "apple" in the str string.
Object-oriented programming concepts

>>> str = "apple orange tangerine apple pear grapes"


>>> rfind(str,"apple")
File input/output
23
Python's intrinsic functions

>>> find(str, "apple") #find finds the first occurrence


0
Formatting, parsing, and manipulating strings
index(s, sub, [start],[end])
like and
find()
with
oneJava
difference.
Interfacing with the works
Java APIs
working
with
StreamsWhen find() can't
locate a substring, it returns a 1; when index() can't, it throws an exception.
Using Python and Java Swing to create GUIs

>>> find(str, "commodore")


Working with SQL and JDBC(TM)
-1
Python and Java applets
>>> index(str, "commodore")
Traceback (innermost last):
In addition, the book contains instructions for downloading and installing the Python
File "<stdin>", line 1, in ?
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
File "D:\Apps\Python\Lib\string.py", line 226, in index
and numerous code samples make this book a useful learning experience.
ValueError: substring not found in string.index
Whether you are a sophisticated computer user new to programming or a serious

rindex(s, sub, [start],[end]) searches from the back of the string for a substring. It's like
application developer, Python Programming with the Java(TM) Class Libraries will
rfind(), but throws an exception if it fails.
give you insight into the power of Python and the know-how to put it to work.

Find"green" in the str string.

777

>>> str = "blue blue blue green red red red"


>>> rindex(str,"green")

15
Find"purple" .

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

>>> rindex(str, "purple")


Publisher: Addison Wesley
Traceback (innermost last):
Pub Date: June 28, 2002
File "<stdin>",
line 1, in ?
ISBN: 0-201-61616-5
File
"D:\Apps\Python\Lib\string.py",
line 243, in rindex
Table of

Pages: 640
ValueError:
substring
not found in string.index
Contents
by ease of use,
richness
of expression,
and concise
syntax, Python
has
count(s, sub,Characterized
[start],[end])
finds
the number
of occurrences
of a substring
in a string.
remained a premier programming language for more than a decade, and is used by
Count"blue" in the
str string.
novices
and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
>>> str = "blue
bluedevelopment.
blue green red red red"
application

>>> count(str, "blue")


3
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
>>> count(str,
"red")
capabilities
and shows the ways that Python interfaces with Java APIs for professional
3
application development.
Count"red".

replace(str, Python
old,Programming
new, [max])
replaces
one substring
with a new
one. The
argument
with the
Java(TM)
Class Libraries:
A Tutorial
formax
Building
Web
specifies the numberand
of occurrences
you want replaced.
The default
all occurrences.
Enterprise Applications
with Jython
covers is
important
topics such as:

Create a string with four "apple" substrings.


Fundamental programming concepts, including statements, expressions,
>>> str = "apple,interpreters,
apple,and
apple,
compilersapple"
Replace the first "apple"
with "pear"
.
Python
basics, including
operators, string formatting, namespaces, classes, errors,

and exceptions

>>> replace(str, "apple", "pear", 1)


'pear, apple, apple,
apple'
Object-oriented
programming concepts
Replace every occurrence of
"apple"
with "orange" .
File
input/output

>>> replace(str, Python's


"apple",
intrinsic"orange")
functions
'orange, orange, orange, orange'
Formatting, parsing, and manipulating strings

Splitting and Joining:


split(), splitfields(), join(), joinfields()
Interfacing with the Java APIs and working with Java Streams
split(s, [sep], [maxsplit])
Using Python and and
Javasplitfields(s,
Swing to create GUIs [sep], [maxsplit]) both
split a string into a sequence. With the sep argument you can specify what you want to use for the
Working with SQL
andor
JDBC(TM)
separatorthe default is whitespace
(spaces
tabs). The maxsplit optional argument allows you to
specify how many items you want to break up; the default is all.
Python and Java applets
Here, with one line of code, we parse an address containing five fields. (Try to do this with Java, C, Delphi, or
In addition, the book contains instructions for downloading and installing the Python
Visual Basicyou can't.)
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous
code samples make thisMain
book aSt.,
useful learning
experience.
>>> input_string
= "Bill,Gates,123
WA, 65743"

>>>
>>>
...
...
...

fname, lname, street, state, zip = split(input_string,",")


print """Whether you are a sophisticated computer user new to programming or a serious
application developer,
Python Programming with the Java(TM) Class Libraries will
Name: %(fname)s
%(lname)s
give
you
insight
into
the
power of Python and the know-how to put it to work.
Street: %(street)s
%(state)s, %(zip)s""" % locals()

777

Name: Bill Gates


Street: 123 Main St.

WA, 65743

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

A Few Things to Note

Publisher: Addison Wesley


Pub Date: June 28, 2002

You can assignISBN:


multiple
variables to a sequence (Chapter 12).
0-201-61616-5

Table of
Pages: 640
Contents
Thelocals() built-in function

(Chapter 9) returns a dictionary that contains the


variables
in
a
local
namespace,
so
the
statement
Characterized by ease of use, richness
of expression, and concise syntax, Python has
>>> locals()["lname"]
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
returns
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
'Gates'

This tutorial
begins with
coverage
of some of or
thesequences
basics of Python
Using
The% format
string operator
works
with dictionaries
(Chapterprogramming.
3).
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
Here we demonstrate that split() and splitfields() do the same thing:
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
>>> split (input_string)
application'Main',
development.'St.,', 'WA,', '65743']
['Bill,Gates,123',
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web

>>> splitfields(input_string)
and Enterprise Applications with Jython covers important topics such as:
['Bill,Gates,123', 'Main', 'St.,', 'WA,', '65743']

Here's an example demonstrating


the default
operationconcepts,
for split()
:
Fundamental
programming
including
statements, expressions,

interpreters, and compilers

>>> split("tab\tspace word1 word2


word3\t\t\tword4")
['tab', 'space', Python
'word1',
'word2',
'word3',
'word4']
basics, including operators, string formatting,
namespaces, classes, errors,
and exceptions

join(words, [sep]) and joinfields(words, [sep]) also do the same thing. Here's our last
example showing how to build
an address string
from a sequence
Object-oriented
programming
concepts of fields:

>>> seq = (fname,Filelname,


street, state, zip)
input/output
>>> input_string = join(seq, ",")
>>> print input_string
Python's intrinsic functions
Bill,Gates,123 Main St., WA, 65743
Formatting, parsing, and manipulating strings
The next two examples demonstrate the similarities of join() and joinfields():
Interfacing with the Java APIs and working with Java Streams

>>> seq = ("1","2","3","4","5")


>>> join(seq, "#")
Using Python and Java Swing to create GUIs
'1#2#3#4#5'
Working with SQL and JDBC(TM)

>>> joinfields(seq,"#")
Python and Java applets
'1#2#3#4#5'
In addition, the book contains instructions for downloading and installing the Python
language
and the Java
Development
Kit (JDK).strip()
Terminology, definitions, explanations,
Stripping and
Parsing:
lstrip(),
rstrip(),
and numerous code samples make this book a useful learning experience.
When you parse strings, you often need to get rid of whitespace. This is what the stripping functions do. They're
Whether you are a sophisticated computer user new to programming or a serious
handy and convenient; I think you'll use them quite a bit.
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

Whitespace Variables

Publisher:
Addison
Whitespace is defined
by the
public Wesley
variable whitespace in the string module. This code
Date: June 28, 2002
contains a tab andPub
spaces:

ISBN: 0-201-61616-5
Table
>>> ofwhitespace
Pages: 640
Contents

'\ 11 '

Characterized by ease of use, richness of expression, and concise syntax, Python has
Thelstrip(s) (left
strip) function
leadinglanguage
whitespace
thethan
left)a in
the string.
remained
a premierremoves
programming
for (on
more
decade,
and isThe
used by
rstrip(s) (rightnovices
strip) function
removes the
trailing
whitespace
therelationship
right). The to
strip(s)
function
and professionals
alike.
In particular,
its (on
close
Java(TM) makes
the
two
languages,
when
used
in
combination,
ideal
for
Web
and
distributed
enterprise
removes both leading and trailing whitespace. Here's an example of all three:
application development.

>>> str = "

String

String "

This tutorial begins with coverage of some of the basics of Python programming. Using
>>> lstrip(str)
plenty of skill-building exercises and interactive programming sessions, this book will
'String
String
'
help those new to programming
develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
>>> rstrip(str)
capabilities and shows the ways that Python interfaces with Java APIs for professional
'
String
applicationString'
development.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
>>> strip(str)
and Enterprise Applications with Jython covers important topics such as:
'String
String'
programming
concepts, including
statements,
expressions,
Adjusting Text: Fundamental
ljust(), rjust(),
center(),
zfill(),
expandtabs()
interpreters, and compilers
The functions for adjusting text are as handy and convenient as the parsing functions. You'll use them a lot,
Python basics, including operators, string formatting, namespaces, classes, errors,
particularly for attractive report printing.
and exceptions
Theljust(s, width) function left-justifies a string to a given width. The rjust(s, width)
Object-oriented
programming
concepts centers a string to a given width. Here are
function right-justifies it. The
center(s,
width) function
examples of all three:
File input/output

>>> rjust("String",20)
Python's intrinsic functions
'
String'
Formatting, parsing, and manipulating strings

>>> rjust ("str",20)


'
str' with the Java APIs and working with Java Streams
Interfacing
Using Python and Java Swing to create GUIs
>>> ljust("String",20)
'String
'
Working with SQL and JDBC(TM)

>>> ljust("str",20)
Python and Java applets
'str
'
In addition, the book contains instructions for downloading and installing the Python

>>> center("str",20)
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
'
str and numerous'code samples make this book a useful learning experience.
>>> center("String",20)
Whether you are a sophisticated computer user new to programming or a serious
'
String
'
application developer,
Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

zfill(snum,width) pads a numeric string with leading zeros.

777

>>> zfill("0.1", 10)


'00000000.1'

expandtabs(s,tabsize)
converts tabs
that
equal
the widthAofTutorial
the tabsize
argument.
Python Programming
withinto
thespaces
Java
Class
Libraries:
for Building
Web and Enterprise Applications with Jython

Create a string with By


tabs
denoted
by \t.
Richard
Hightower

>>> str = "tab\ttab\ttab\t"

Publisher: Addison Wesley

Pub Date: June 28, 2002


Expand the tabs to five spaces.
Table of

ISBN: 0-201-61616-5

>>> Contents
expandtabs(str,
Pages:5)
640
'tab
tab
tab '
Characterized by ease of use, richness of expression, and concise syntax, Python has
Expand the tabs to ten
spaces. a premier programming language for more than a decade, and is used by
remained
novices and professionals alike. In particular, its close relationship to Java(TM) makes
>>> expandtabs(str,10)
the two languages, when used in combination, ideal for Web and distributed enterprise
'tab
tab
tab
'
application development.
Expand the tabs to twenty
spaces.begins with coverage of some of the basics of Python programming. Using
This tutorial

plenty of skill-building exercises and interactive programming sessions, this book will

>>> expandtabs(str, 20)


help those new to programming develop an understanding of concepts and practical
'tab
tab
tab
'

Summary

techniques. For experienced programmers, the book demonstrates Python's breadth of


capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.

Python Python
Programming
theset
Java(TM)
ClasstoLibraries:
A and
Tutorial
Building
Web in
In its standard distribution,
provideswith
a rich
of functions
manipulate
parsefor
strings
not found
and
Enterprise
Applications
with
Jython
covers
important
topics
such
as:
other programming languages. My guess is that you'll use these functions a lot.

CONTENTS
Fundamental programming
concepts, including statements, expressions,
interpreters, and compilers
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
Object-oriented programming concepts
File input/output
Python's intrinsic functions
Formatting, parsing, and manipulating strings
Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs
Working with SQL and JDBC(TM)
Python and Java applets
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
CONTENTS
Web and Enterprise Applications with Jython
By Richard Hightower

Chapter 11. Interfacing


with Java
Publisher: Addison Wesley
Pub Date: June 28, 2002

Using the Java APIs


ISBN: 0-201-61616-5
Table of
Java Types
Pages: 640
Contents
Java Constructors
Java ArraysCharacterized
and jarray by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
Java Arrays and Methods
novices and professionals alike. In particular, its close relationship to Java(TM) makes
Bean Properties
the two languages, when used in combination, ideal for Web and distributed enterprise
Properties application development.
Java Event Handling
tutorial
begins with coverage of some of the basics of Python programming. Using
SubclassingThis
Java
Classes
plenty of skill-building exercises and interactive programming sessions, this book will
Advanced Topics
help those new to programming develop an understanding of concepts and practical
Summary techniques. For experienced programmers, the book demonstrates Python's breadth of

capabilities and shows the ways that Python interfaces with Java APIs for professional
Terms in This Chapter
application development.
Python
Libraries: A Tutorial for Building Web
Applet Programming with the Java(TM) Class
-h option
and Enterprise Applications with Jython covers important topics such as:
AWT
Interface
Fundamental programming concepts,Java
including
Base class
API statements, expressions,
interpreters, and compilers
Bean
JFC
Python basics, including operators, string formatting, namespaces, classes, errors,
and
exceptions
Built-in
object
Object wrapper
BufferObject-oriented programming concepts
Packing

File
input/output
Content
pane

Primitive type

Python's intrinsic functions


Constructor

Property

Formatting, parsing, and manipulating


strings
Coupling
Public
function
with Java Streams
DesignInterfacing
pattern with the Java APIs and working
self
GUIs
Event Using Python and Java Swing to create
Superclass
Event Working
handler with SQL and JDBC(TM) Subclass
Event Python
listenerand Java applets

Typecode

In
addition,
the book contains instructions for
First
class object
Typedownloading
signature and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and
numerous code samples make this book
a useful learning experience.
Frame
Unicode
Whether
a sophisticated computer user new to programming or a serious
get() and you
set()are
methods
application developer, Python Programming with the Java(TM) Class Libraries will
Java's vast array of application
programming
interfaces
(APIs) and
helpthe
youknow-how
build GUIs,
optimize
network
give you insight
into the power
of Python
to put
it to work.
communications, create distributed objects, build components, work with databases, and design Web
applications. This chapter is about how to use them with Jython.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

Downloading the Java Documentation

Publisher:
Addison go
Wesley
To get the most out
of this chapter,
to the JavaSoft site (http://www.java.sun.com) and
Pub
Date:
June 28, 2002
download the Java
API
documentation.

ISBN: 0-201-61616-5

Table of
Contents

Pages: 640

Using the Java APIs

Characterized by ease of use, richness of expression, and concise syntax, Python has
premier
programming
more thansession.
a decade,
and two
is used
by from the
To see how easy it isremained
to use thea Java
APIs,
follow alonglanguage
with thisfor
interactive
Import
classes
novices
and
professionals
alike.
In
particular,
its
close
relationship
to
Java(TM)
makes
Java package javax.swing: JFrame and JButton. (We'll cover these classes in depth in Chapter 13.)
the two languages, when used in combination, ideal for Web and distributed enterprise
>>> from javax.swing
import JFrame, JButton
application development.
Create an instance ofThis
each.
tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
>>> frame = JFrame()
help those new to programming develop an understanding of concepts and practical
>>> button = techniques.
JButton("Hello
Java
APIs")the book demonstrates Python's breadth of
For experienced
programmers,
capabilities and shows the ways that Python interfaces with Java APIs for professional
(Note that you create Java instances and Python instances in the same way.)
application development.
Add the button instance to the content pane.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython
covers
importantto
topics
suchcontent
as:
>>> pane = frame.getContentPane()
# get
access
the
pane

>>> pane.add(button)
# add the button to the content pane
javax.swing.JButton
... programming concepts, including statements, expressions,
Fundamental
interpreters, and compilers
Pack the components in the frame.

>>> frame.pack()
Make the frame visible.

>>>
>>>
>>>
...
...
>>>

Python basics, including operators, string formatting, namespaces, classes, errors,


and exceptions
Object-oriented programming concepts

frame.visible = 1
# make the frame visible
File input/output
# define the function that does the event handling
def button_clicked(event):
Python's intrinsic functions
print "Hello from Java APIs!!!!"
Formatting, parsing, and manipulating strings

button.actionPerformed = button_clicked

#set up the event handler

Interfacing with the Java APIs and working with Java Streams
Figure 11-1 shows the output you get after clicking the button several times. Figure 11-2 shows the form we just
Using Python and Java Swing to create GUIs
created.
Working
with11-1.
SQLOutput
and JDBC(TM)
Figure
from the Button Event
Python and Java applets
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower
Publisher: Addison Wesley
Pub Date: June 28, 2002

Table of
Contents

ISBN: 0-201-61616-5
Pages: 640

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
Figure 11-2. JFrame Form
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
Java classes are pretty much like Python classes. Importing classes are the same in the two languages, except that
Java classes come from
packages
whereas with
Python
come
fromLibraries:
modules.AThere
are afor
few
other slight
Python
Programming
theclasses
Java(TM)
Class
Tutorial
Building
Web
differences, which we'll
cover
later,
that
don't
change
the
basic
similarities.
and Enterprise Applications with Jython covers important topics such as:

Java Types

Fundamental programming concepts, including statements, expressions,


interpreters, and compilers
In this section we're going to cover how Python handles the conversion from Java types when you pass
arguments to Java methodsPython
and when
those
methodsoperators,
return values.
though,namespaces,
let's briefly cover
theerrors,
Java basic
basics,
including
stringFirst,
formatting,
classes,
types:
and exceptions
Object-oriented programming concepts

boolean contains true or false

File input/output

char contains Unicode characters


Python's intrinsic functions

byte contains 8-bit signed integers

Formatting, parsing, and manipulating strings

short contains 16-bit signed integers

Interfacing with the Java APIs and working with Java Streams

int contains 32-bit signed integers

Using Python and Java Swing to create GUIs

long contains 64-bit signed integers

Working with SQL and JDBC(TM)

float contains 32-bit floating-point numbers


Python and Java applets

double contains 64-bit floating-point numbers


In addition, the book contains instructions for downloading and installing the Python

String contains
Unicode
charactersKit (JDK). Terminology, definitions, explanations,
languagea string
and theofJava
Development
and numerous code samples make this book a useful learning experience.

array contains arrays of objects or primitive types

Whether you are a sophisticated computer user new to programming or a serious


application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

Primitive versus Basic Types

Publisher:
I define as Java basic
types Addison
all of theWesley
primitive types plus any classes that have special operators or
literal notation. Thus,
for example,
can add String instances together using the + operator,
Pub Date:
June 28,you
2002
and you can create them
using
literals, so, by definition, strings are a basic Java type. I hope this
ISBN:
0-201-61616-5
Table of
terminology catchesPages:
on. 640
Contents

Characterized by ease of use, richness of expression, and concise syntax, Python has

Passing Arguments
Javaprogramming
Methods language for more than a decade, and is used by
remained to
a premier

novices and professionals alike. In particular, its close relationship to Java(TM) makes
One of the key differences
calling
methods
Java and calling
in Python
is that Java
expects Java
the twobetween
languages,
when
used inincombination,
idealthem
for Web
and distributed
enterprise
types. At first, this may
seem complex,
but Jython takes care of all of the conversion transparently. All you need
application
development.
to know is how a Java type maps to the corresponding Python type so that, for example, when you read the Java
API documentation you
which
Python
to pass
a particular
method.
Thisknow
tutorial
begins
with type
coverage
of to
some
of the basics
of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
Java has many more help
basicthose
typesnew
thantoPython
has. Fordevelop
example,
Python Float
is like the
double.
programming
anthe
understanding
of concepts
andJava
practical
Python has no Double
, so youFor
can experienced
use Floatprogrammers,
whenever youthe
need
a Java
double Python's
or float
.
techniques.
book
demonstrates
breadth
of
capabilities and shows the ways that Python interfaces with Java APIs for professional
Again, Java has three ways to describe an integerbyte,short, and intwhich take up varying levels of
application development.
space. Python has just one integer type, Integer, that can take the place of any Java integer type. Fewer types
mean less to worry about
andProgramming
remember. with the Java(TM) Class Libraries: A Tutorial for Building Web
Python
and Enterprise Applications with Jython covers important topics such as:
Table 11-1 shows the mapping from Java types to Python types for calling Java methods. Notice that eleven Java
types map to only five Python types. The Python Integer alone corresponds to four Java types ( boolean,
byte,short, and int).Fundamental
The Python String
type concepts,
corresponds
to threestatements,
Java types.expressions,
programming
including
interpreters, and compilers

Getting Return Values from Java Methods

Python basics, including operators, string formatting, namespaces, classes, errors,


and exceptions
Jython converts the values returned from Java methods to Python types. Table 11-2 lists these mappings. The
conversion also works withObject-oriented
Java primitive-type
object wrappers,
programming
conceptsas illustrated in Table 11-3.
File input/output
Putting Things Together
Python's intrinsic functions
Let's use the Java class Float to demonstrate the Python conversion of basic Java data types. Float, from
thejava.lang package, converts
variousparsing,
Java basic
to a Java float
Formatting,
andtypes
manipulating
strings .
In particular, we'll look at the
following
Float
methods:
Interfacing
with
the Java
APIs and working with Java Streams

Using Python and Java Swing to create GUIs

static Float valueOf(String str) converts a string to a float


Working with SQL and JDBC(TM)

float floatValue() gets the primitive float wrapped in a Float instance


Python and Java applets

static boolean isInfinite(float v) Boolean checks to see if the float is


infinite and returns
a primitive
In addition,
the book contains instructions for downloading and installing the Python

language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Table 11-1. Java/Python Type Mapping
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Java

PythonPython
Programming with the Java Class Libraries: A Tutorial for Building
Web and
Enterprise
Applications
String
(must
have lengthwith
1) Jython
By Richard Hightower

char
boolean
Integer (false = zero, true = nonzero)
byte,short,int, Publisher:
Integer
Addison Wesley
long
Long
(in the
Pub Date: June
28,range
2002 of Java long or integer)
float,double
Float
ISBN: 0-201-61616-5
Table of

Pages:
640
java.lang.String
String
Contents
byte[]
String
Characterized by ease of use, richness of expression, and concise syntax, Python has
array[]
Jarray
remained
a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
Table
11-2.
Java/Python
Type
Mappings
for Return
Values
This
tutorial
begins
with coverage
of some
of the basics
of Python
programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
new to programming
develop an understanding of concepts and practical
Java Basic Type help those
Returned
Python Type
techniques.
For
experienced
programmers,
book
char
One-characterString"a" orthe
'a'
butdemonstrates
not "ab" Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
boolean
Integer
(true = 1, false = 0)
application
development.

byte
Integer
Python
Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
short
Integer
and Enterprise Applications with Jython covers important topics such as:
int
Integer
long
Long
Fundamental
programming concepts, including statements, expressions,
float,double
Float
interpreters, and compilers
java.lang.String String
java.lang.Class Python
JavaClass
(org.python.core.PyJavaClass
)
basics, including
operators, string formatting, namespaces,
classes, errors,
and
exceptions
Instance
PyInstance (org.python.core.PyInstance)
ClassInstance[] Object-oriented
Array (contains
objects ofconcepts
class or subclass of ClassInstance)
programming
File input/output
Python's intrinsic functions
Table 11-3. Java/Python Mappings for Object Wrappers
Formatting, parsing, and manipulating strings
Java Object Wrapper Interfacing
Python with
Typethe Java APIs and working with Java Streams
java.lang.Char
String (with one character)
Using
Python and Java Swing to create GUIs
java.lang.Integer Integer

java.lang.Boolean
Integer
Working
with SQL and JDBC(TM)
java.lang.Byte
Integer
and Java applets
java.lang.Short Python
Integer
java.lang.Long
Long
In addition,
the book contains instructions for downloading and installing the Python
java.lang.Double
languageFloat
and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous
code samples make this book a useful learning experience.
java.lang.Float
Float
Whether
youthat
are aa method
sophisticated
computer
to programming
a serious
Thestatic keyword
specifies
isn't bound
to a user
class new
instance;
that is, it canorbe
called without a
application developer, Python Programming with the Java(TM) Class Libraries will
class instance being created. Static methods in Java are thus like functions defined in Python modules. If you're
give you insight into the power of Python and the know-how to put it to work.
confused, follow along with this quick example.
Import the Java class Float.

777

>>> from java.lang import Float

Python
Programming
with
the Java
Demonstrate a function
that returns
a Float
wrapper
object.Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard
Hightower
>>>
#valueOf
returns
a java.lang.Float
>>> myFloatObject = Float.valueOf("1.1")
Publisher: Addison Wesley
>>> type(myFloatObject)
<jclass org.python.core.PyFloat
at -1329353172>
Pub Date: June 28, 2002
ISBN: 0-201-61616-5

Table of
Notice
from640
valueOf() (stored in myFloatObject) is converted to a Python
that the value returned
Pages:
Contents
Float
.

Characterized by ease of use, richness of expression, and concise syntax, Python has
Now let's use the isInfinite() method to demonstrate the return of a primitive. In this case,
remained a premier programming language for more than a decade, and is used by
isInfinite() returns
a primitive Boolean.
novices and professionals alike. In particular, its close relationship to Java(TM) makes
languages, when used in combination, ideal for Web and distributed enterprise
>>> myBooleanthe=two
Float.isInfinite(myFloatObject)
application
>>> type(myBoolean) development.

<jclass org.python.core.PyInteger
at -820007380>
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty
of skill-building
exercises and interactive
programming
sessions, this book will
Before I can show you
an example
of floatValue()
, I need to explain
Java constructors.
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application about
development.
A Reminder
Returning Types in CPython and
Python Programming with theJython
Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
In CPython, types are returned as follows.
Return an Int.

Fundamental programming concepts, including statements, expressions,


interpreters, and compilers

>>> myint = 1
Python basics, including operators, string formatting, namespaces, classes, errors,
>>> type(myint)
<type 'int'>and exceptions
Return a Float. Object-oriented programming concepts

input/output
>>> myfloat File
= 1.1
>>> type(myfloat)
Python's intrinsic functions
<type 'float'>
Formatting, parsing, and manipulating strings
Here's how types are returned in Jython.
Interfacing with the Java APIs and working with Java Streams
Return an Int.
Using Python and Java Swing to create GUIs

>>> myint = 1
>>> type(myint)
Working with SQL and JDBC(TM)
<jclass org.python.core.PyInteger at -820007380>
Python and Java applets
Return a Float.
In addition, the book contains instructions for downloading and installing the Python
>>> myfloat=1.1
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
>>> type(myfloat)
and numerous code samples make this book a useful learning experience.

<jclass org.python.core.PyFloat at -1329353172>


Whether you are a sophisticated computer user new to programming or a serious
The followingapplication
will work developer,
the same inPython
both Python
and Jython.
IntType
and
Programming
withImport
the Java(TM)
Class
Libraries will
FloatType
from
the
types
module.
give you insight into the power of Python and the know-how to put it to work.

>>> from types import IntType, FloatType

777

Test to see if myint is IntType. If so, print "Integer type".

>>> if(type(myint)==IntType):print
"Integer
Python Programming with the Java Class
Libraries: type"
A Tutorial for Building
Integer type
Web and Enterprise Applications with Jython
By Richard Hightower

Test to see if myfloat is FloatType; if so, print "Float type".


Publisher: Addison Wesley

>>> if(type(myfloat==FloatType)):print "Float type"


Float type Pub Date: June 28, 2002

Table of
Contents

ISBN: 0-201-61616-5
Pages: 640

Java Constructors

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
All instances of Java classes are of type Instance ( org.python.core.PyInstance). Here I use a
novices and professionals alike. In particular, its close relationship to Java(TM) makes
constructor to create a date. In Java, as in Python, a constructor is a method in a class, so this example
the two languages, when used in combination, ideal for Web and distributed enterprise
demonstrates a method returning an instance of class Date.
application development.

>>> from java.util import Date


This tutorial begins with coverage of some of the basics of Python programming. Using
>>> date = Date()
plenty of skill-building exercises and interactive programming sessions, this book will
>>> type(date)
help those new to programming develop an understanding of concepts and practical
<jclass org.python.core.PyInstance at -1204237921>

techniques. For experienced programmers, the book demonstrates Python's breadth of


capabilities
and shows
ways in
thatJython,
Pythonhowever.
interfaces
with Java
for PyInstance
professional
Constructors don't behave
like regular
Java the
methods
Instead,
theyAPIs
convert
s
application
development.
of the class even if the class is a Java primitive wrapper. (Remember, methods that return primitive wrappers are
converted to the corresponding Python types.) In this context, the Integer and Float constructors return
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
PyInstances.
and Enterprise Applications with Jython covers important topics such as:
Import the Java primitive wrappers Integer and Float.

Fundamental programming concepts, including statements, expressions,


interpreters, and compilers

>>> from java.lang import Integer, Float

Create the Java primitive wrapper Integer with the constructor, and view its type.
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
>>> i = Integer(1)

>>> type(i)
Object-oriented programming concepts
<jclass org.python.core.PyInstance at -1292653012>
File input/output
Create the Java primitive wrapper Float with the constructor, and view its type.
Python's intrinsic functions

>>> f = Float(1.1)
>>> type (f)
Formatting, parsing, and manipulating strings
<jclass org.python.core.PyInstance at -1292653012>
Interfacing with the Java APIs and working with Java Streams
As you can see, the primitive types don't come back as corresponding Python types but as PyInstances.
Conversely, the valueOf()
class
Integer
and class
Float returns the Java primitive object
Usingmethod
Pythonofand
Java
Swing to create
GUIs
wrappers Integer and Float, respectively, which are converted to corresponding Python types. In short, the
Working
SQL
and JDBC(TM)
rules that apply to Java methods
don'twith
apply
to Java
constructors.
Now back to floatValue()
Here's
anapplets
example of Python converting the Java return values of int and
Python. and
Java
float to Python Integer and Float:
In addition, the book contains instructions for downloading and installing the Python
>>> type(i.intValue())
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
<jclass org.python.core.PyInteger
at book
-820007380>
and numerous code samples make this
a useful learning experience.

Whether you are a sophisticated computer user new to programming or a serious


>>> type(f.floatValue())
application developer, Python Programming
with the Java(TM) Class Libraries will
<jclass org.python.core.PyFloat
at -1329353172>
give you insight into the power of Python and the know-how to put it to work.
Convert the object wrapper instance java.lang.Float to PyFloat.

777

>>> type(Float.valueOf("1.1"))
<jclass org.python.core.PyFloat at -1329353172>

Convert the object wrapper


java.lang.Float
PyInteger
Pythoninstance
Programming
with the Java to
Class
Libraries: .A Tutorial for Building
Web and Enterprise Applications with Jython

>>> type(Integer.valueOf("1"))
By Richard Hightower
<jclass org.python.core.PyInteger at -820007380>
Publisher: Addison Wesley

By the way, instances of Java classes used to be of type JavaInstance


Pub Date: June 28, 2002
(org.python.core.PyJavaInstance), but that changed with the release of Jython 1.1.

ISBN: 0-201-61616-5
Table of
Pages:
640
from org.python.core
import
Contents

>>>
PyJavaInstance
>>> type(b)==PyJavaInstance
Characterized by ease of use, richness of expression, and concise syntax, Python has
0

remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two
languages,
when used in combination,
idealMinutiae
for Web and distributed enterprise
For
Beginners:
Why the
application development.

You can program


Python
without
how Python
takes of
care
of Java
types. However,
This in
tutorial
begins
withunderstanding
coverage of some
of the basics
Python
programming.
Using
when you dealplenty
with of
theskill-building
more advanced
Java APIs,
the minutiae
we're dealingsessions,
with here
may
exercises
and interactive
programming
this
book will
become important.
The good
news
is that Jython
takes an
care
of all Java type
conversion
help those
new to
programming
develop
understanding
of concepts
and practical
transparently,techniques.
so 95 percent
the time youprogrammers,
don't need to the
worry.
that other 5 Python's
percent that
may of
Forofexperienced
bookIt'sdemonstrates
breadth
get you.
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.

Java ArraysPython
and Programming
jarray with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
The closest thing to a Java array in Python is a tuple. Remember that a tuple is immutable and a list is mutable.
Like a list, a Java array is mutable but, like a tuple, it's of fixed length. You may think that a tuple or a list is a
Fundamental programming concepts, including statements, expressions,
likely candidate for an array, but that's not exactly the case. You see, an array is like a homogeneous tuple or
interpreters, and compilers
listevery item in it is of the same type; but a tuple is heterogeneousitems in it can be of different types. A lot
of Java methods have JavaPython
arrays as
arguments,
so when
you pass
anformatting,
array to a Java
method, Python
to
basics,
including
operators,
string
namespaces,
classes,has
errors,
guarantee that it will be homogeneously
typed.
and exceptions
Just a note: Because they'reObject-oriented
strongly typed, programming
Java arrays canconcepts
hold Java objects or primitive types.
Jython adds PyArray class support for Java arraysorg.python.core.PyArray to be exact.
File input/output
Instances of PyArray are returned from Java methods that return Java arrays. You need to create instances of
PyArray to pass to Java Python's
methodsintrinsic
that require
arrays. Python makes creating a PyArray painless with the
functions
jarray module, which defines two public functions, described in Table 11-4.
Formatting, parsing, and manipulating strings

Interfacing with the Java APIs and working with Java Streams

No Built-In Java Objects

Using Python and Java Swing to create GUIs

A Java object is only an instance of a class. There are no other object types, so there are no built-in
Working with SQL and JDBC(TM)
Java objects as there are in Python. The closest things Java has to Python's built-in objects are
strings and arrays, which
special
syntax.
Pythonrequire
and Java
applets

In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Table 11-4. jarray Public Functions
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
Function
Description
give you insight
into the power of Python and the know-how to put it to work.
array(sequence,
Creates an array of a specific type with values from the sequence; the
array is the same size as the sequence
type)

777

zeros(length,
type)

Creates an empty array the length of the length parameter

the Java Class Libraries: A Tutorial for Building


Thetype argumentPython
for bothProgramming
zeros() andwith
array()
can be either a string or a Java class object. You can
Web and Enterprise Applications with Jython
use a single-character string typecode to specify that the array will hold primitive values. Table 11-5 shows the
By Richard Hightower
typecodes and their primitive types.
Publisher:
Addison
Wesley
Here's an example of creating
arrays
with the
array() and zeros() methods from the jarray module.
Pub Date: June 28, 2002

Create a Boolean array using


the array()
method.
ISBN:
0-201-61616-5

Table of

Pages: 640

>>> Contents
from jarray import array, zeros
>>> seq = (1,0,1,0,1,0)
Characterized by ease of use, richness of expression, and concise syntax, Python has
>>> booleanArray
= aarray(seq,
'z')language for more than a decade, and is used by
remained
premier programming
novices and professionals alike. In particular, its close relationship to Java(TM) makes
Inspect its contents. the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
>>> booleanArray
array([1, 0, This
1, tutorial
0, 1,begins
0],with
boolean)
coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will

>>> print `booleanArray`


help those new to programming develop an understanding of concepts and practical
array([1, 1, techniques.
1, 1, 1,
0], boolean)
For experienced programmers, the book demonstrates Python's breadth of
See what type it is.

capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.

>>> booleanArray
Programming
the Java(TM) Class Libraries: A Tutorial for Building Web
array([1, 0, Python
1, 0,
1, 0], with
boolean)
and Enterprise Applications with Jython covers important topics such as:

>>> print `booleanArray`


array([1, 1, 1, 1,
1, 0],programming
boolean)concepts, including statements, expressions,
Fundamental

Typecode

'z'
'c'
'b'
'h'
'i'
'l'
'f'
'd'

interpreters, and compilers


Table 11-5. Typecodes and Primitive types
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
Primitive Type
Object-oriented programming boolean
concepts

char
byte
Python's intrinsic functions short
int
Formatting, parsing, and manipulating
long strings
Interfacing with the Java APIs float
and working with Java Streams
double
File input/output

Using Python and Java Swing to create GUIs


Change its values.

Working with SQL and JDBC(TM)

>>> booleanArray[1]=1
Python and Java applets
>>> booleanArray[3]=1
>>> booleanArray
In addition, the book contains instructions for downloading and installing the Python
array([1, 1, 1, 1, 1, 0], boolean)

language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and
numerousoncode
samples
thisonbook
a useful(alearning
You can use the same
operations
an array
that make
you use
a sequence
tuple orexperience.
a list). Here's an example:
Whether
are a sophisticated computer user new to programming or a serious
>>> for boolean
inyou
booleanArray:
application
developer,
Python Programming with the Java(TM) Class Libraries will
...
print `boolean`
give
you
insight
into
the
power of Python and the know-how to put it to work.
...
1
1
1
1

777

1
Python Programming with the Java Class Libraries: A Tutorial for Building
0
Web and Enterprise Applications with Jython
>>> len(booleanArray)
By Richard Hightower
6
Publisher: Addison Wesley

Even though an array isPub


mutable,
it's still of fixed length; that means that you can't append to it as you can a
Date: June 28, 2002
Python list. If you try, you'll get an attribute error.

ISBN: 0-201-61616-5
Table of
Pages:
640
booleanArray.append(1)
Contents

>>>
Traceback (innermost last):
Characterized
by ease1,
of use,
of expression, and concise syntax, Python has
File "<console>",
line
in richness
?
remained
a
premier
programming
language
for more than a decade, and
AttributeError: instance of 'org.python.core.PyArray'
hasis used
no by
attribute 'appen
novices and professionals alike. In particular, its close relationship to Java(TM) makes
used in combination, ideal for Web and distributed enterprise
Let's create an array the
withtwo
thelanguages,
zeros()when
method.
application development.

>>> IntArray = zeros(10,'i')


This tutorial begins with coverage of some of the basics of Python programming. Using
>>> print IntArray
of skill-building
interactive
array([0, 0, plenty
0, 0,
0, 0, 0,exercises
0, 0,and0],
int)programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
As the above example
shows, you
can
think of PyArray
essentially
as demonstrates
a Python built-in
type that's
specific
techniques.
For
experienced
programmers,
the book
Python's
breadth
of to
Jython. Like other features
Jython
has
for integrating
withPython
Java, PyArray
s areJava
transparent
the programmer
capabilities
and
shows
the ways that
interfaces with
APIs fortoprofessional
development.
(when returned fromapplication
a Java method).
Creating one is easy with Jython's jarray module.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web

Java Arraysand
and
Methods
Enterprise
Applications with Jython covers important topics such as:

Let's see some examples of using arrays to get values from and pass values to Java methods. We'll use three
Fundamental
programming
including
statements,
expressions, , and
methods of the Java String
class (from
the java.langconcepts,
package):
valueOf()
,getBytes()
interpreters,
compilers
getChar(), which are described
in and
Table
11-6.

Pythontakes
basics,
including
string
namespaces,
classes,
errors,
Since the valueOf() method
char[]
asoperators,
an argument,
weformatting,
need to create
an array of
primitive
type
and
exceptions
char. In Java the [] notation denotes an array.
Object-oriented programming concepts
Table 11-6. Example Java String Class Methods
File input/output
Method

Description
static String valueOf(char[] data)
Converts an array of primitive type
Formatting, parsing, and manipulating stringschar into a string
byte[] getBytes()
Returns
byte data associated
Interfacing with the Java APIs and working with
Java the
Streams
with a string
Using
Python and Java
to create GUIsCopies characters from the string
void getChars(int
srcBegin,
intSwing
srcEnd,
char [] dst, int dstBegin)
into a char array
Working with SQL and JDBC(TM)

Python's intrinsic functions

Importjava.lang.String and jarray.array.


Python and Java applets

>>> from java.lang import String


In addition, the book contains instructions for downloading and installing the Python
>>> from jarray import array

language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous
samples make
this bookJava
a useful
Create a sequence whose
items cancode
be converted
into primitive
type learning
char. experience.
Whether you are a sophisticated
user new'o',
to programming
or a serious
>>> seq = ('H','e','l','l',
'o', computer
' ', 'W',
'r', 'l'
, 'd')
application
developer,
Python
Programming
with
the
Java(TM)
Class
Libraries will
>>> seq
give you
insight
into the
of Python
and the
know-how
put it to work.
('H', 'e', 'l',
'l',
'o',
' power
', 'W',
'o',
'r',
'l',to 'd')
Use the array() method to create a PyArray of primitive Java type char.

777

>>> data = array(seq, 'c')

>>> data #Display


just to show
you
what
in it.
Python Programming
with the
Java
Classis
Libraries:
A Tutorial for Building
array(['H', 'e',
'l',
'l',Applications
'o', ' ',
'W',
'o', 'r', 'l', 'd'], char)
Web and
Enterprise
with
Jython
By Richard Hightower

ThevalueOf() method, which takes a char[]argument (a char array), takes the array of Java primitive
chars and turns it intoPublisher:
a Java string
.
Addison Wesley
Pub Date: June 28, 2002
>>> str = String.valueOf(data)
ISBN: 0-201-61616-5
>>> Table
print
of str

Pages:
640
Hello
World
Contents

ease of use,
richness of expression, and concise syntax, Python has
Use getBytes()Characterized
to demonstratebyreturning
an array.
remained a premier programming language for more than a decade, and is used by
>>> hi = String("Hello
Cruel alike.
World")
novices and professionals
In particular, its close relationship to Java(TM) makes
>>> bytes = hi.getBytes()
the two languages, when used in combination, ideal for Web and distributed enterprise
>>> bytes
#display
what is in bytes
application
development.

array([72, 101, 108, 108, 111, 32, 67, 114, 117, 101, 108, 32, 87, 111, 114,
Thisbyte)
tutorial begins with coverage of some of the basics of Python programming. Using
108, 100],
plenty
skill-building
and interactive
programming
sessions, to
this book
will
>>> chr(bytes[0])of #The
chr exercises
function
converts
an integer
a character
help
those
new
to
programming
develop
an
understanding
of
concepts
and
practical
'H'
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities
and(Java
showsarray),
the ways
thatthe
Python
interfaces
APIs
for professional
In Java, you often supply
the buffer
which
method
fills withwith
the Java
output
results.
The
getChars() method
expectsdevelopment.
a character buffer (char array), but it doesn't matter what's in it because it's
application
only for output. Thus, we can use the jarray.zeros() method to create an empty, or zero-initialized,
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
buffer.
and Enterprise Applications with Jython covers important topics such as:
Importzeros() and String() .
Fundamental
programming concepts, including statements, expressions,
>>> from jarray import
zeros
interpreters,
andString
compilers
>>> from java.lang
import
Python basics, including
Create an instance of java.lang.String
. operators, string formatting, namespaces, classes, errors,
and exceptions

>>> hi = String("Here we are now")


Object-oriented programming concepts
Use the zeros() method to create the char array, dst.
File input/output

>>> dst = zeros(10, 'c')


Python's intrinsic functions
Use the getChars() method to fill dst.
Formatting, parsing, and manipulating strings

>>> hi.getChars(0,10, dst, 0)


Interfacing with the Java APIs and working with Java Streams
>>> print dst
array(['H', 'e', 'r', 'e', ' ', 'w', 'e', ' ', 'a', 'r'...], char)
Using Python and Java Swing to create GUIs
Dealing with Java arrays in Python demonstrates how the Python language keeps things simple.
Working with SQL and JDBC(TM)

Bean PropertiesPython and Java applets


In addition, the book contains instructions for downloading and installing the Python
With Jython, you can use JavaBeans properties like instance attributes, which makes it easy to interact with Java
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
classes. You can also use them as keyword arguments to Java class constructors (like Tcl/Tk).
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

About JavaBeans

Addison
Wesley
JavaBeans have Publisher:
properties and
events,
much like ActiveX controls, which are a lot like OLE
Date:
28, 2002
controls (OCXs),Pub
which
areJune
like Visual
Basic controls (VBX). To make a short story long,
JavaBeans allow IDEISBN:
(Integrated
Development Environments) to do mundane things that you used
0-201-61616-5
Table of
to have to write codePages:
for. 640
Contents

ease of
use, richness
of expression,
Python
has
In Java, you need theCharacterized
set() and by
get()
methods
to define
a property. and
Let'sconcise
say thatsyntax,
you create
a property
remained
a
premier
programming
language
for
more
than
a
decade,
and
is
used
by
calledname that you want to be both read and write. You can define two methods for it.
novices and professionals alike. In particular, its close relationship to Java(TM) makes
public void setName(String
the two languages, whenname)
used in combination, ideal for Web and distributed enterprise
public Stringapplication
getName()
development.
(By the way, void in
Java
meansbegins
that the
method
doesn't
returnofanything.)
wantprogramming.
name to be read-only,
This
tutorial
with
coverage
of some
the basicsIfofyou
Python
Using
define only the getName()
method.
plenty of skill-building
exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
In Python, you can access
the name
property as follows
(assuming
you defined
the methods
in abreadth
class called
techniques.
For experienced
programmers,
the book
demonstrates
Python's
of
myJavaClass). capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.

>>> instance = myJavaClass()


>>> instance.name
= "Rick"with the Java(TM) Class Libraries: A Tutorial for Building Web
Python Programming
>>> print instance.name
and Enterprise Applications with Jython covers important topics such as:
Rick
You can also set name when
you call the
constructor. concepts, including statements, expressions,
Fundamental
programming
interpreters, and compilers

>>> instance = myJavaClass(name= "Rick")


>>> print instance.name
Python basics, including operators, string formatting, namespaces, classes, errors,
Rick
and exceptions
Object-oriented
We'll show some real examples
of this laterprogramming
in the chapter.concepts

Properties

File input/output

Python's intrinsic functions


Sometimes properties are more complex than basic Java typesfor example, a property can be a type of class.
and
manipulating
You can set properties thatFormatting,
expect classparsing,
instances
with
tuples that strings
correspond to the constructor of the property
type. (This only works for things like java.awt.Dimension.)
Interfacing with the Java APIs and working with Java Streams
An example of this is the setSize() method of javax.swing.JFrame. The size property expects
and Java
Swing
to create
GUIs integer arguments.
an instance of class Size,Using
whosePython
constructor
expects
width
and height
Working with SQL and JDBC(TM)
The following code recaps what we've learned so far about using properties. We'll show how to create a frame
and set its size property with a tuple, and we'll show the frame's visible property. Don't worry that you
Python and Java applets
don't know JFC/Swing. I'll walk you through it.
In addition, the book contains instructions for downloading and installing the Python
Import the JFrame class.
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerousimport
code samples
make this book a useful learning experience.
>>> from javax.swing
JFrame
Whether you are a sophisticated computer user new to programming or a serious
Create a JFrame instance.
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.
>>> f = JFrame()
What happens? Nothing. That's because the default for creating a JFrame instance is that it be invisible. If we
want it to be visible, we can pass it the visible property keyword argument as follows, or we can just set the
property like any other instance attribute.

777

Python in
Programming
with the Java
Set the visible property
the constructor.

>>> f =

Class Libraries: A Tutorial for Building


Web and Enterprise Applications with Jython
By Richard
Hightower
JFrame
(visible=1)

Set the visible property


as a property.
Publisher:
Addison Wesley
Pub Date: June 28, 2002

>>> f.visible = 0ISBN: 0-201-61616-5


of
>>> Table
f.visible
= 1
Pages: 640

Contents

As you can see, even though visible, the frame isn't very big. We can set the frame size by passing it a size
Characterized by ease of use, richness of expression, and concise syntax, Python has
parameter.
remained a premier programming language for more than a decade, and is used by
novices and professionals alike.visible=1)
In particular, its close relationship to Java(TM) makes
>>> f = JFrame(size=(250,250),
the two languages, when used in combination, ideal for Web and distributed enterprise
Now we have a big, application
blank frame,development.
which we can make even bigger.

>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>

tutorial begins with coverage of some of the basics of Python programming. Using
f.size = This
500,500
plenty of= skill-building
exercises and interactive programming sessions, this book will
f.background
0,255,255
help those
to programming develop an understanding of concepts and practical
f.background
= new
255,0,255
techniques.
For experienced programmers, the book demonstrates Python's breadth of
f.background
= 0,255,255
capabilities
and shows the ways that Python interfaces with Java APIs for professional
f.background = 255,255,0
application
development.
f.background
= 0,255,0
f.background = 255,0,0
Python Programming
f.background
= 0,0,255with the Java(TM) Class Libraries: A Tutorial for Building Web

and Enterprise Applications with Jython covers important topics such as:
No, I didn't forget to tell you what the above code does. I didn't want to tell you. I want to shame those of you
who aren't doing the examples into putting down the book and starting to program.
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers

Event Properties

Python basics, including operators, string formatting, namespaces, classes, errors,


and exceptions
You can think of event properties
as properties that take methods as arguments. As a Java programmer, you can
think of them as a way to implement Java events. In Python, you set an event property so you can be notified
Object-oriented
concepts
when an event happens. Notification
comesprogramming
when the class
instance calls the method you passed to the property
when the event occurred.
File input/output
For example, JButton has an event property called actionPerformed, which represents the button
Python's
intrinsic
functions
being pressed. Whenever this
happens,
the method
passed to actionPerformed is called. This is much
easier to explain with code.
Formatting, parsing, and manipulating strings
Import the JButton and JFrame classes from the javax.swing package, and create an instance of JFrame.
Interfacing with the Java APIs and working with Java Streams
Set its size at 200,200 pixels, and make it visible.

Using Python and Java Swing to create GUIs

>>> from javax.swing import JButton, JFrame


>>> f = JFrame(visible=1,
size=(200,200))
Working with SQL
and JDBC(TM)
Define an event handler forPython
JButton
. applets
and Java

>>> def Hello(event):


In addition, the book contains instructions for downloading and installing the Python
...
printlanguage
"Hello
World"
and the
Java Development Kit (JDK). Terminology, definitions, explanations,
...
and numerous code samples make this book a useful learning experience.
Create an instance ofWhether
JButton
button, and
pass theuser
event
handler
as the actionPerformed
you called
are a sophisticated
computer
new
to programming
or a serious
property.
application developer, Python Programming with the Java(TM) Class Libraries will

give you insight into the power of Python and the know-how to put it to work.

>>> button = JButton("Hello World", actionPerformed=Hello)

777

Add the button to the frame, and pack the frame with the components.

>>> f.getContentPane().add(button)

javax.swing.JButton[,0,0,0x0,invalid,layout=javax.swing.OverlayLayout,
Python Programming with the Java Class Libraries: A Tutorial for Building
alignmentX
Web and Enterprise Applications with Jython
...
By Richard Hightower
>>> f.pack()
Publisher: Addison Wesley

If you hit the "Hello World" button, you'll see "Hello World" print to the console. Note that the argument
Pub Date: June 28, 2002
the event handler needs is the event object passed to it.
ISBN: 0-201-61616-5
Table of
Pages: 640
youContents
program in Java 1.1 or later, you know that AWT

If
(and JFC) components are handled by passing an
instance of a class that implements a specific event handler interface. In Jython, things are much easier because
Characterized
by ease
use,objects.
richness of expression, and concise syntax, Python has
functions and methods
are considered
first of
class
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
Java Event Handling
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
Here's an example of Java event handling in Jython. It does the same thing the example in the previous section
This tutorial
did but in the Java (Jython)
way. begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those newimport
to programming
develop
an understanding of concepts and practical
>>> from javax.swing
JFrame,
JButton
techniques.
For
experienced
programmers,
the book demonstrates Python's breadth of
>>> from java.awt.event import ActionListener
capabilities
and
shows
the
ways
that
Python
interfaces with Java APIs for professional
>>> class hello(ActionListener):
application development.
...
def actionPerformed(self,
event):

...
...
>>>
>>>
>>>
>>>
>>>
>>>
>>>

print "Hello"
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
f = JFrame()

b = JButton("Hello from Java Events")


hi = hello() Fundamental programming concepts, including statements, expressions,
b.addActionListener(hi)
interpreters, and compilers
f.getContentPane().add(b)
f.pack()
Python basics, including operators, string formatting, namespaces, classes, errors,
f.visible = 1and exceptions

I think you'll prefer the more


Pythonesque way
of doing things
because it's brief and easy. Unfortunately,
Object-oriented
programming
concepts
however, you need to know the Java way to understand the Jython way. For example, the only way to know that
JButton supports an event
is to know that it supports the method addActionListener(),
Fileproperty
input/output
and that addActionListener() takes an instance of the ActionListener interface (an interface is
intrinsic functions has a method called actionPerformed(). In
a totally abstract class), andPython's
that ActionListener
other words, the inventors of Jython expect you to know the Java event model.
Formatting, parsing, and manipulating strings
So then, Jython isn't really for beginners. To help in this regard, I've created a module to let you inspect the Java
with the Java
and
with
event model, and I've addedInterfacing
a section explaining
it inAPIs
detail
soworking
that when
youJava
readStreams
the Java APIs you'll know
how the events map.
Using Python and Java Swing to create GUIs

Thejinfo Module Working with SQL and JDBC(TM)


andallows
Java applets
I've created a module calledPython
jinfo that
you to inspect Java class event properties. Let's look at JButton
(javax.swing.JButton).
In addition, the book contains instructions for downloading and installing the Python
language
andJButton
the Java Development
Kit (JDK). Terminology, definitions, explanations,
Import the jinfo module
and the
class.
and numerous code samples make this book a useful learning experience.

>>> from jinfo import *


Whether you are
a sophisticated
computer user new to programming or a serious
>>> from javax.swing
import
JButton
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight
into the
power
Python
and the know-how
to put .it to work.
Use the getEventsInfo()
method
to view
theofevents
associated
with JButton

>>> getEventsInfo(JButton, 1)
>>>

777

Nothing happened here


because
the events associated
JButton
are defined
in JButton
's superclass.
Python
Programming
with the with
Java
Class Libraries:
A Tutorial
for Building
Thus, we need to find
out and
whatEnterprise
that superclass
is.
Web
Applications
with Jython
By Richard Hightower

>>> JButton.superclass
<jclass javax.swing.AbstractButton
at 1250890579>
Publisher: Addison Wesley
Pub Date: June 28, 2002

Now we can query its events.

>>>

ISBN: 0-201-61616-5
Table of
Pages:
from javax.swing 640
import AbstractButton
Contents

>>> getEventsInfo(AbstractButton)
Characterized
by ease of use, richness offor
expression,
and interface
concise syntax, Python has
[<beanEventProperty
itemStateChanged
event
remained
a
premier
programming
language
for
more
than
a decade, and is used by
java.awt.event.ItemListener at -1327819950>,
novices
and
professionals
alike.
In
particular,
its
close
relationship
to Java(TM)
<beanEventProperty actionPerformed for event interface
jav makes
the
two
languages,
when
used
in
combination,
ideal
for
Web
and
distributed
enterprise
a.awt.event.ActionListener at -1284828334>,
application
development.
<beanEventProperty stateChanged for event interface
javax.swing.event.ChangeListener at -1331489966>]

This tutorial begins with coverage of some of the basics of Python programming. Using
of skill-building
interactive
sessions, this book will
The code above is a plenty
little hard
to read, so I'llexercises
show youand
another
way toprogramming
use the getEventsInfo()
help
those
new
to
programming
develop
an
understanding
of
concepts
and practical
information.
techniques. For experienced programmers, the book demonstrates Python's breadth of
>>> events = capabilities
getEventsInfo(AbstractButton)
and shows the ways that Python interfaces with Java APIs for professional
>>> len (events)
application development.

3
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
>>> printEventProperty(events[0])
and Enterprise Applications with Jython covers important topics such as:

Event Property:
itemListener
Defined in:
java.awt.event.ItemListener
Fundamental programming concepts, including statements, expressions,
Event:
java.awt.event.ItemEvent
interpreters, and compilers

Event properties Python


for basics,
java.awt.event.ItemEvent:
including operators, string formatting, namespaces, classes, errors,
itemSelectable
and exceptions Type: org.python.core.PyBeanProperty
stateChange
Type: org.python.core.PyBeanProperty
item
org.python.core.PyBeanProperty
Object-oriented Type:
programming
concepts
File input/output
Public Event fields
for java.awt.event.ItemEvent:
static final ITEM_FIRST
Type: int
intrinsic functions
static finalPython's
ITEM_LAST
Type: int
static final ITEM_STATE_CHANGED
Type: int
parsing, and manipulating strings
static finalFormatting,
SELECTED
Type: int
static finalInterfacing
DESELECTED
Type: int
with the Java APIs and working with Java Streams
Now you can look up the event information in the class's java.awt.event.ItemListener interface
Using Python and Java Swing to create GUIs
andjava.awt.event.ItemEvent class in the Java API documentation. The properties that the event
passes to itemListener
are also
shown.
Working
with
SQL and JDBC(TM)
Let's do another example. We're
with
this event because we've used it in many of the previous examples.
Pythonfamiliar
and Java
applets

>>> printEventProperty(events[1])
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,

Event Property:
actionListener
and numerous code samples
make this book a useful learning experience.
Defined in:
java.awt.event.ActionListener
Event:
java.awt.event.ActionEvent
Whether you are a sophisticated
computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will

Event properties
java.awt.event.ActionEvent:
give youfor
insight
into the power of Python and the know-how to put it to work.
modifiers
Type: org.python.core.PyBeanProperty
actionCommand
Type: org.python.core.PyBeanProperty

777

Public Event fields for java.awt.event.ActionEvent:

static
static
static
static
static
static
static

Table of

final
Type:
intA Tutorial for Building
PythonSHIFT_MASK
Programming with the Java Class
Libraries:
final
CTRL_MASK
Type: int
Web and
Enterprise Applications with Jython
final
META_MASK
Type: int
By Richard
Hightower
final ALT_MASK
Type: int
final
ACTION_FIRST
Type: int
Publisher:
Addison Wesley
final
ACTION_LAST
Type: int
Pub Date: June 28, 2002
final ISBN:
ACTION_PERFORMED
Type: int
0-201-61616-5
Pages: 640

Contents
We can
use this information to determine which classes to look up in the documentation: ActionListener
andActionEvent. We can use the fields from ActionEvent in our event handler. The following code
Characterized by ease of use, richness of expression, and concise syntax, Python has
uses this information to display the Modifiers and ActionCommand of ActionEvent:
remained a premier programming language for more than a decade, and is used by
novices and professionals
alike. In particular,
its close relationship to Java(TM) makes
>>> from javax.swing
import JButton,
JFrame
the
two
languages,
when
used
in
combination,
ideal for Web and distributed enterprise
>>> f = JFrame(visible=1)
application
development.
>>> b = JButton("Hello")

>>> def hello(event):


This tutorial begins with coverage of some of the basics of Python programming. Using
...
print "Modifiers: " + `event.modifiers`
plenty of skill-building exercises and interactive programming sessions, this book will
...
print "ActionCommand: " + `event.actionCommand`
help those new to programming develop an understanding of concepts and practical
...
techniques. For experienced programmers, the book demonstrates Python's breadth of
>>> b.actionPerformed = hello
capabilities and shows the ways that Python interfaces with Java APIs for professional
>>> f.contentPane.add(b)
application development.
javax.swing.JButton[,0,0,0x0,invalid,layout=javax.swing.OverlayLayout,`
alignmentX
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
...
and Enterprise Applications with Jython covers important topics such as:
...
>>> f.pack()
Fundamental programming concepts, including statements, expressions,
Try hitting the button a fewinterpreters,
times. You'll
seecompilers
that you can print out the attributes of the event based on the
and
information obtained using getEventsInfo() and printEventProperty(). If you want to know
basics,
including
string java.awt.event.ActionEvent
formatting, namespaces, classes, errors,
what the properties for the Python
event were
used
for, lookoperators,
them up under
and
exceptions
in the Java documentation.
Object-oriented programming concepts

Advanced Topic: The JavaBeans Event Model in Detail


File input/output
The Java 1.1 event model was introduced so that you would no longer have to subclass a GUI component in
Python's
intrinsic
functions
order to handle events, as you
did with
the Java
1.0 version. JFC, AWT, and JavaBeans use the version 1.1 event
model, which defines the following:
Formatting, parsing, and manipulating strings
Interfacing
Source the origin of
the eventwith the Java APIs and working with Java Streams
Using
Python
Javathat
Swing
to create
GUIs
Listener a class that
listens
for anand
event,
is, the
event handler
SQL and JDBC(TM)
Event informationWorking
about thewith
event
In this model, to define an Python
event you
subclass a class from EventObject, which contains event
andhave
Javatoapplets
information. One piece of information is the source property, which provides the event's origin. In our last
In addition,instance
the bookcalled
contains
instructions
downloading
and installing theinstance
Python passed
example, we had a JButton
b, which
was thefor
source
of the ActionEvent
Development
Kit (JDK).
Terminology,
explanations,
to the event method language
handler (inand
thethe
lastJava
example
this method
was called
hello()definitions,
).
and numerous code samples make this book a useful learning experience.
An event listener registers itself with the event source, which notifies the listener when the event happens by
you aremust
a sophisticated
computer
new tosource
programming
a serious
calling a method on Whether
it. All listeners
implement the
methoduser
the event
needs toor
call.
To do so they
developer, Python Programming with the Java(TM) Class Libraries will
have to implement aapplication
listener interface.
give you insight into the power of Python and the know-how to put it to work.
An interface is like an abstract Java class, so it can't be instantiated. It defines a contract between the event
source and the event listener. Classes that want to listen for ActionEvents, for example, must implement the
ActionListener interface. All listener interfaces must extend the java.util.EventListener
interface.

777

Python
Programming
the that
Java
Class
Libraries:
A Tutorial
for Building
Classes that act as event
sources
must define with
methods
allow
event
listeners to
register themselves.
These
Web
and
Enterprise
Applications
with
Jython
methods typically take the form addXXListener(XXListener listener) and
By Richard Hightower
removeXXListener(XXListener
listener), where XX is the event name. The class maintains a
list of listeners registered for that event. When the event occurs, the event source class has the code to notify
Publisher: Addison Wesley
them.
Pub Date: June 28, 2002

The individual methods in the


listener
interface need only one argument, of type Event. For example,
ISBN:
0-201-61616-5
Table of
XXListener
's methodsPages:
take one
argument of XXEvent. Let's say you've written a class that monitors stock

640
Contents
prices (we'll call it StockPriceChecker), which acts as an event source for an event called
StockPrice. AsCharacterized
the stock pricebyrises
falls richness
above orofbelow
certainand
levels,
the class
sends
out has
easeand
of use,
expression,
concise
syntax,
Python
StockPrice events
to all classes
thatprogramming
are registeredlanguage
to receive
remained
a premier
forthem.
more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
TheStockPriceChecker
class has
the following
methods forideal
registering
the two languages,
when
used in combination,
for WebStockPriceEvent
and distributed enterprise
listener objects:
application development.

This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding listener)
of concepts and practical
removeStockPriceListener(StockPriceListener
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities
andmight
shows
thethe
ways
that Python
interfaces
with Java
forStockPrice
professional
TheStockPriceEvent
class
have
following
methods
that provide
dataAPIs
on the
application development.
event:

addStockPriceListener(StockPriceListener listener)

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web

getPrice()
returns a float
andEnterprise
Applications with Jython covers important topics such as:
getName() returns the name of the stock
Fundamental programming concepts, including statements, expressions,
Contained in StockPriceEvent
thecompilers
data that StockPriceChecker sends out to the
interpreters, isand
StockPrice event listeners.
Python basics, including operators, string formatting, namespaces, classes, errors,
TheStockPriceListener
interface can have the following methods, which define specific occurrences
and exceptions
of events:
Object-oriented programming concepts

priceDropped(StockPriceEvent
event)
File input/output
priceIncreased(StockPriceEvent
Python's intrinsic functions event)
Any class implementing theFormatting,
interface can
register
with
the event source,
parsing,
and
manipulating
strings StockPriceChecker, to receive
StockPrice events.
Interfacing with the Java APIs and working with Java Streams

Using Python and Java Swing to create GUIs

Design Patterns

Working with SQL and JDBC(TM)

Java is chockful of design


are ways to organize classes and objects to solve
Pythonpatterns.
and JavaThese
applets
recurring software engineering problems. The Java event model is an example of the
Observer/Observable
design
also known
as Publish
and Subscribe.
Itsinstalling
purpose is
reduce
In addition,
the pattern,
book contains
instructions
for downloading
and
thetoPython
coupling of the
source and the sink
listener). Kit (JDK). Terminology, definitions, explanations,
language
Java (the
Development
and numerous code samples make this book a useful learning experience.
Once you've mastered Python programming and read Object-Oriented Analysis and D esign with
Applications (Booch,
sure to readcomputer
Design Patterns
et al., 1995).
Whether1994),
you aremake
a sophisticated
user new(Gamma
to programming
or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power
of in
Python
andyou
thedon't
know-how
put it to work.
Now, if you use the StockPriceChecker
class
Python,
have totoimplement
the
StockPriceListener interface and register an instance with StockPriceChecker.
StockPriceChecker has two event properties corresponding to the methods in the interface of
StockPriceListenerpriceDropped and priceIncreasedso you can pass an event
handler function that has one argument, which is passed as StockEvent.

777

Programming with the Java Class Libraries: A Tutorial for Building


If you're confused atPython
this point,
fear not. We'll do lots of examples using both Python and Java event handling
Web and Enterprise Applications with Jython
when we cover GUI programming in Chapter 13.
By Richard Hightower

Publisher: Addison Wesley

Technical Tip: Bean Introspection

Pub Date: June 28, 2002

Table of
Jython uses
Contents

ISBN: 0-201-61616-5
640
the beanPages:
introspection
features

of Java, which provide the ability to inspect a bean's


properties, events, and methods. Any Java class can be a bean if it follows certain design patterns
Characterized
by ease of use,
richness of
expression,
andnaming
conciseconventions,
syntax, Python has
in method, interface,
and class-naming
conventions.
Also,
instead of
remained
a
premier
programming
language
for
more
than
a
decade,
andtoisactions
used by
developers can define BeanInfo classes that describe the methods corresponding
novices
and
professionals
alike.
In
particular,
its
close
relationship
to
Java(TM)
makes
such as event registration.
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.

Subclassing Java Classes

This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
You can subclass Java
classes
classes. Here's
an example
of subclassing
the Java
class
help
those like
newPython
to programming
develop
an understanding
of concepts
and
practical
java.util.Date
(from MyDate.py):
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities
and Date
shows the ways that Python interfaces with Java APIs for professional
from java.util
import
application development.

class MyDate(Date):
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
def __init__(self,
num=None):
and Enterprise Applications with Jython covers important topics such as:
if num is None:
Date.__init__(self)
else:
Fundamental programming concepts, including statements, expressions,
Date.__init__(self,
num)
interpreters,
and compilers
def __str__(self):
basics, including operators, string formatting, namespaces, classes, errors,
str Python
= Date.toString(self)
and
exceptions
str = "MyDate: " + str
return str
Object-oriented programming concepts

Working with JavaFile


Constructors
input/output
Python's
functions constructor, just as you do in regular Python. As we
When you subclass a Java class,
youintrinsic
call its superclass's
saw, the MyDate.py example subclassed the Date class from java.lang and defined two constructors that
Formatting, parsing, and manipulating strings
calledDate's base class constructors.
with
the Java APIs and working
with
Java
As an exercise, look up theInterfacing
constructors
of java.lang.Date
in the
Java
APIStreams
documentation. You'll find
them in a section called Constructor Summary.
Using Python and Java Swing to create GUIs
The constructor of Date is defined in Java as
Working with SQL and JDBC(TM)

Date ()

Python and Java applets

You call it from Python like this:


In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
Date.__init__(self)
and numerous code samples make this book a useful learning experience.
The second constructor of Date is defined in Java as
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
Date (long date)
give you insight into the power of Python and the know-how to put it to work.
You call it from Python like this:

777

Date.__init__(self, num)

Here's how to call both


Date
constructors: with the Java
Python
Programming

class

Class Libraries: A Tutorial for Building


Web and Enterprise Applications with Jython
MyDate(Date):
By Richard Hightower

def __init__(self, num=None):


ifPublisher:
num is
None:
Addison Wesley
Date.__init__(self)
Pub Date: June 28, 2002
else:
ISBN: 0-201-61616-5
Date.__init__(self, num)
Table of
Pages: 640

Contents

In Java, constructors are special language constructs that always have the same name as that of their class. In
Characterized
ease of
use, __init__
richness of expression,
syntax,
Python, the constructor
is always a by
method
called
. You call and
Javaconcise
constructors
in Python
Python has
just as you
remained
a
premier
programming
language
for
more
than
a
decade,
and
is
used
by
do Python constructors; however, you can only do so in your subclass's constructor.
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
Working with application
Java Methods
development.
When subclassing a This
Java tutorial
class, you
can call
methodsoffrom
Java
class
youprogramming.
can from a Python
begins
withall
coverage
somea of
thebase
basics
of that
Python
Usingbase
class. In our MyDate.py
example,
we subclass
Date and
and interactive
add a __str__
method.sessions, this book will
plenty
of skill-building
exercises
programming
help those new to programming develop an understanding of concepts and practical
def __str__(self):
techniques. For experienced programmers, the book demonstrates Python's breadth of
str = Date.toString(self)
capabilities and shows the ways that Python interfaces with Java APIs for professional
str = "MyDate:
" + str
application development.

return str
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
Unlike Python methods,
Java methods
can be overloaded,
which
essentially
means
that
a Java
and Enterprise
Applications
with Jython
covers
important
topics
such
as: class can have
several methods with the same name. An example of this is java.io.OutputStream, which defines
threewrite() methods:
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers

abstract void write(int b)


Python basics, including operators, string formatting, namespaces, classes, errors,

void write(byte[]
b)
and exceptions
void write (byte[]
b, int
off, concepts
int len)
Object-oriented
programming
As you can see, these methods
be called with different argument types.
File can
input/output
To subclass OutputStream
, weintrinsic
need a way
to override any or all of the write() methods. The following
Python's
functions
example shows how to do this. (Before we get started, however, read up on the OutputStream class in the
Java API documentation.) Formatting, parsing, and manipulating strings

from java.io import


OutputStream
Interfacing
with the Java APIs and working with Java Streams
import types
Using Python and Java Swing to create GUIs

class OutputScreen (OutputStream):


Working with
SQL and JDBC(TM)
def write (self,
b=None,
off=None, len=None):
if (type(b) is types.IntType):
Python and Java applets
print b
elif
(off
is contains
None):
In addition, the book
instructions for downloading and installing the Python
print
language and the Java b
Development Kit (JDK). Terminology, definitions, explanations,
else:
and
numerous code samples make this book a useful learning experience.
print b[off:off+len]
Whether you are a sophisticated computer user new to programming or a serious
This code imports OutputStream
, a Java
classProgramming
from the java.io
OutputScreen
subclasses
application developer,
Python
withpackage.
the Java(TM)
Class Libraries
will
OutputStream give
and overrides
its
write()
methods
(all
three
versions).
Thus,
each
clause
of
you insight into the power of Python and the know-how to put it to work. the if
statement in write() mimics a different overloaded signature of OutputStream'swrite()s.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

Overloading

Publisher:like
Addison
Wesley
Strongly typed languages
Java, C++,
and Delphi allow method overloading. In other words,
June 28,
2002
they allow more Pub
thanDate:
one method
with
the same name but different signatures. The type of the
method's arguments defines
the signature. With overloaded methods, the signature determines
ISBN: 0-201-61616-5
Table of
which method is actually
being
Pages:
640 invoked.
Contents

Python doesn'tCharacterized
allow methodbyoverloading
on type
signatures and
because
it isn't
a strongly
ease of use,based
richness
of expression,
concise
syntax,
Pythontyped
has
language. (Some
may say
it's loosely
typed; Pythonians
prefer
the term
To
remained
a premier
programming
language
for more
than"dynamically
a decade, andtyped.").
is used by
override a method
from
subclass in Python,
theparticular,
class mustitsdefine
method withtothe
same name.
novices
anda professionals
alike. In
closearelationship
Java(TM)
makes
the two languages, when used in combination, ideal for Web and distributed enterprise
To illustrate, the following
codedevelopment.
mimics the functionality of void write(int b) by determining that the
application
first argument, b, is of type Integer.
This tutorial begins with coverage of some of the basics of Python programming. Using
if (type(b) is
types.IntType):
plenty
of skill-building exercises and interactive programming sessions, this book will
print bhelp those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
This code mimics thecapabilities
functionality
voidthewrite(byte[]b)
by determining
that off
wasn't passed
andofshows
ways that Python interfaces
with Java APIs
for professional
(and that the first type
was
not
Integer
).
application development.

elif (off is Python


None):
Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
print and
b Enterprise Applications with Jython covers important topics such as:
This mimics the functionality of void write (byte[]b, int off, int len) by a process of
Fundamental programming concepts, including statements, expressions,
elimination.
interpreters, and compilers

else:
print b[off:off+len]
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
Let's test each of these scenarios. Start the overload.py module from Jython with the i option and try the
programming concepts
following statements in an Object-oriented
interactive session.

from jarray import


array
File input/output
Python's intrinsic functions
screenOut = OutputScreen()
Formatting, parsing, and manipulating strings
screenOut.write(33)
Interfacing with the Java APIs and working with Java Streams

seq = [0,1,2,3,4,5,6,7,8,9,0xA,0xB,0xC,0xD,0xE,0xF]
bytearray = array(seq,
'b')
Using Python
and Java Swing to create GUIs
screenOut.write(bytearray)
Working with SQL and JDBC(TM)
screenOut.write(bytearray, 5, 14)

Python and Java applets


Essentially, we're calling all three write() methods. Here's the code step by step.
In addition, the book contains instructions for downloading and installing the Python
Import the array()
function
from
to create JavaKit
byte
arraysTerminology,
(byte[]). definitions, explanations,
language
and
the jarray
Java Development
(JDK).
and numerous code samples make this book a useful learning experience.

from jarray import array

Whether you are a sophisticated computer user new to programming or a serious


Create an OutputScreen
called
ScreenOut
.
applicationinstance
developer,
Python
Programming
with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

screenOut = OutputScreen()

777

Invoke the first form of the write() method, void write(int b).

screenOut.write(33)

Python
Programming
with the
Class
Create a byte array for
an argument
for the second
and Java
third forms
ofLibraries:
write()A. Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower
[0,1,2,3,4,5,6,7,8,9,0xA,0xB,0xC,0xD,0xE,0xF]

seq =
bytearray = array(seq, 'b')

Publisher: Addison Wesley

Invoke the second formPub


of write()
write(byte[] b).
Date: June,void
28, 2002
ISBN: 0-201-61616-5

Table of
screenOut.write(bytearray)

Pages: 640
Contents

Invoke the last form of write(),void write (byte[]b, int off, int len) .
Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming
screenOut.write(bytearray,
5, 14) language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
The output should bethe two languages, when used in combination, ideal for Web and distributed enterprise
application development.

33
some
of the
basics
of Python
array([0, 1, This
2, tutorial
3, 4,begins
5, with
6, coverage
7, 8, of9,
10,
11,
12,
13, programming.
14, 15], Using
byte)
plenty
of
skill-building
exercises
and
interactive
programming
sessions,
this book will
array([5, 6, 7, 8, 9, 10], byte)
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
Advanced Topics
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
To understand what I'm going to talk about here, you should have some Java background and have read the API
Python Programming
documentation for OutputStream
. with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

Overriding write()
Fundamental programming concepts, including statements, expressions,
Another way to override allinterpreters,
of write()
forms is to override only the abstract version and then just call the
and'scompilers
others. You can also use a variable number of arguments for write() and then just use the apply()
Python basics,
operators,
string
formatting,
namespaces,
method to execute the nonabstract
forms. including
Let me show
you what
I mean.
(The following
codeclasses,
is fromerrors,
and exceptions
Overload.py.)

class OutputScreen2
(OutputStream):
Object-oriented
programming concepts
def write(self, *args):
File input/output
# If the args length is greater than one or the first
# argument is not type IntType, use the apply method.
Python's intrinsic
if len(args)
> functions
1 or not type(args[0]) is types.IntType:
Formatting, parsing, and manipulating strings

# Use the apply method to call other forms:


#
void
write(byte[]
b)Java Streams
Interfacing
with the
Java APIs
and working with
#
void write(byte[] b, int off, int len)
apply(OutputStream.write,
Using
Python and Java Swing to create GUIs (self,)+args)
# Otherwise just print the first argument
Working
SQL and
JDBC(TM) b).
# , with
i.e.,
write(int
else:
Python
and Java
applets
print
args[0]
addition,
the bookiscontains
instructions
for downloading 'sand
installingmethod
the Python
To determine which In
form
of write()
being invoked,
OutputScreen2
write()
checks if
language
and
the
Java
Development
Kit
(JDK).
Terminology,
definitions,
the length of the args tuple is greater than 1 or if the first argument isn't an integer. If either isexplanations,
the case, void
samples make[]
thisb book
experience.
write(byte[] and
b)numerous
or void code
write(byte
inta useful
off,learning
int len)
is being called.
Otherwise,write(int b) is being called.
Whether you are a sophisticated computer user new to programming or a serious
developer,
Python
Programming
with the Java(TM), although
Class Libraries
willis much
The code to test this application
(Overload.py)
looks like
the code
to test OutputScreen2
the output
give
you
insight
into
the
power
of
Python
and
the
know-how
to
put
it
to
work.
different.

print "OutScreen2"
screenOut = OutputScreen2()

777

screenOut.write(33)
Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython

seq = [0,1,2,3,4,5,6,7,8,9,0xA,0xB,0xC,0xD,0xE,0xF]
By Richard Hightower
bytearray = array(seq, 'b')
Publisher: Addison Wesley

print "void write(byte[])"


Pub Date: June 28, 2002
screenOut.write(bytearray)
ISBN: 0-201-61616-5

Table of

Pages: 640

Contents
print
"void write(byte[], int off, int len)"
screenOut.write(bytearray,
Characterized by ease of5,
use,5)
richness of expression, and concise syntax, Python has

remained a premier programming language for more than a decade, and is used by
The Java API documentation states, "Applications that need to define a subclass of OutputStream must
novices and professionals alike. In particular, its close relationship to Java(TM) makes
always provide at least a method that writes one byte of output." Basically this means that, if you define void
the two languages, when used in combination, ideal for Web and distributed enterprise
write (int b), the default implementation of the other two write() forms calls void write
application development.
(int b), which is why the output is different. Essentially, write() is called for each item in the byte array
passed to void write(byte[])
and for
each byte
in theofrange
withinofthe
byte array
for voidUsing
This tutorial begins, with
coverage
of some
the basics
Python
programming.
write(byte[],plenty
intof off,
int
len)
.
skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical

Compiling Java
Classes
techniques.
For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application
To build applets, JavaBeans,
anddevelopment.
servlets, or to subclass Python classes in Java, you need to compile the classes
into*.class files. The Jython distribution includes a utility called jythonc to do this.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise
Jython
covers
important
topics such
as:
If you execute jythonc
from the Applications
command linewith
with
the h
option,
it will describe
the command-line
options
for the compiler. Go ahead and try it. (If you're a Jython user, you can type jythonc instead of jpythonc .)
Fundamental
programming
concepts, including statements, expressions,
The following options are used
with jythonc
:
interpreters, and compilers
basics,
including
operators,
string
formatting,
namespaces, classes, errors,
-p the packagePython
option;
puts the
compiled
classes in
the specified
package
and exceptions

-j the jarfile option; puts the compiled classes in a jar file


Object-oriented programming concepts

-d the deep option; compiles Python dependencies of the compiled classes (necessary for creating
input/output
applets that will run File
on most
browsers, including Internet Explorer)
Python's
intrinsic
functions
-c the core option;
compiles
all dependencies
and includes the core Jython libraries (necessary for
creating applets that will run in Netscape Navigator)
Formatting, parsing, and manipulating strings
-a the all option; everything in the core plus the compiler and parser
Interfacing with the Java APIs and working with Java Streams
-b the bean option; puts classes in the jar file and adds a manifest file for the bean (necessary for
creating JavaBeans) Using Python and Java Swing to create GUIs

SQLwhere
and JDBC(TM)
-w the workdirWorking
option; with
specifies
to compile the code (the default puts the code in a directory
under the current directory called jpywork)
Python and Java applets
We'll cover creating a JavaBean and an applet later. For now, using Overload.py, let's create a Python class that
In addition, the book contains instructions for downloading and installing the Python
can be subclassed in Java. Before we can do this with jythonc, we have to put the class in a module with the
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
same name, and the class has to subclass a Java class or interface. To compile the OutputScreen class, we
and numerous code samples make this book a useful learning experience.
need to put it in a file called OutputScreen.py.OutputScreen already subclasses a Java class called
OutputStream.Whether you are a sophisticated computer user new to programming or a serious

application developer, Python Programming with the Java(TM) Class Libraries will
Here's an exercise using the OutputScreen class:
give you insight into the power of Python and the know-how to put it to work.

from java.io import OutputStream


import types

777

# Class OutputScreen is a subclass of Java class OutputStream.

class OutputScreen
(OutputStream):
Python Programming
with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython

def write(self,
*args):
By Richard Hightower
# Addison
If the
args
Publisher:
Wesley

Table of
Contents

length is greater than one or the first


#
argument
is
not type IntType, use the apply method.
Pub Date: June 28, 2002
if len(args)
>
1
or
not
type(args[0]) is types.IntType:
ISBN: 0-201-61616-5
Pages: 640

# Use the apply method to call other forms:


# use, richness
void
write(byte[]
Characterized by ease of
of expression,
and concise b)
syntax, Python has
#
void
write(byte[]
b,and
int
off,
remained a premier programming language for more than a decade,
is used
by int len)
apply(OutputStream.write,
(self,)+args)
novices and professionals alike. In particular, its close relationship to Java(TM) makes
else:
the two languages, when used in combination, ideal for Web and distributed enterprise
# Overide the write (int) method.
application development.
print args[0]

This tutorial begins with coverage of some of the basics of Python programming. Using
Go to the DOS prompt
where
the source code
is located,
then enter
pythoncsessions,
dOutputScreen
plenty
of skill-building
exercises
andand
interactive
programming
this book will at
the command line. help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
development.
jythonc creates aapplication
directory called
jpywork, in which it places the Java source code and the compiled Java

C:\jpybook\chap11>jythonc -d OutputScreen.py
class.

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
C:\jpybook\chap11\jpywork>dir

Directory of C:\jpybook\chap11\jpywork
Fundamental programming concepts, including statements, expressions,

.
<DIR>
08-05-99 5:46p .
interpreters, and compilers
..
<DIR>
08-05-99 5:46p ..
OUTPUT~1 JAV
6,221including
08-05-99
OutputScreen.java
Python basics,
operators,5:46p
string formatting,
namespaces, classes, errors,
OUTPUT~1 CLA
3,305 08-05-99 5:46p OutputScreen.class
and exceptions
OUTPUT~2 CLA
3,224 08-05-99 5:46p OutputScreen$_PyInner.class
Object-oriented programming
concepts
3 file(s)
12,750 bytes
2 dir(s)
2,432.67 MB free
File input/output
There should be one source file called OutputScreen.java and two class files.
Python's intrinsic functions
The following listing shows part of the OutputScreen class.
Formatting, parsing, and manipulating strings

import org.python.core.*;
Interfacing with the Java APIs and working with Java Streams

public class OutputScreen extends java.io.OutputStream implements org.python.


Using Python and Java Swing to create GUIs
...
...
Working with SQL and JDBC(TM)
//The overloaded write method
public void write(int
arg0)
throws java.io.IOException {
Python and
Java applets
PyObject inst = Py.jgetattr(this, "write");
try {In addition, the book contains instructions for downloading and installing the Python
inst._jcallexc(new
Object[]
{Py.newInteger(arg0)}
);
language and the Java Development
Kit (JDK).
Terminology, definitions, explanations,
}
and numerous code samples make this book a useful learning experience.
...
Whether you are a sophisticated computer user new to programming or a serious
...
application developer, Python Programming with the Java(TM) Class Libraries will
}
give you insight
into the power of Python and the know-how to put it to work.
//The write
method
public void write(byte[] arg0, int arg1, int arg2) throws java.io.IOException
PyObject inst = Py.jfindattr(this, "write");
if (inst != null) try {
inst._jcallexc(new Object[] {arg0, Py.newInteger(arg1),

777

}
...

Py.newInteger(arg2)}
); Libraries: A Tutorial for Building
Python Programming
with the Java Class
Web and Enterprise Applications with Jython
By Richard Hightower

...
Publisher: Addison Wesley

else super.write(arg0,
Pub Date: June 28, 2002arg1, arg2);
}
Table of
Contents
public
void

...
...

ISBN: 0-201-61616-5

//The
write method
Pages: 640
write(byte[] arg0) throws java.io.IOException {
PyObject
inst by= ease
Py.jfindattr(this,
"write");
Characterized
of use, richness of expression,
and concise syntax, Python has
if (inst
!=
null)
try
{
remained a premier programming language for more than a decade, and is used by
inst._jcallexc(new
);
novices and professionals alike.Object[]
In particular, {arg0}
its close relationship
to Java(TM) makes
}
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.

else This
super.write(arg0);
tutorial begins with coverage of some of the basics of Python programming. Using
}

plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
The code for the write()
method
that takes only
one argument
thedemonstrates
Python instance
of breadth of
techniques.
For experienced
programmers,
thehas
book
Python's
OutputScreen capabilities
and gets theand
write
from
Then itinterfaces
executeswith
the method.
showsattribute
the ways
thatit.Python
Java APIs for professional
application development.
First it defines void write(int).
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

public void write(int arg0) throws java.io.IOException {

Next it gets the write attribute from the Python instance of OutputScreen, called Py. The attribute is
stored in inst.
Fundamental programming concepts, including statements, expressions,

interpreters, and compilers

PyObject inst = Py.jgetattr(this, "write");


Python basics, including operators, string formatting, namespaces, classes, errors,
Then it executes the attribute.
and exceptions

inst._jcallexc(new Object[] {Py.newInteger(arg0)} );


Object-oriented programming concepts

Now the code has multiple arguments. The forms that were not overridden check to see if the Python instance of
File input/output
OutputScreen has a write() method. If it doesn't, the superclass OutputStream is called; if it
does, the write() method
of theintrinsic
Python instance
Python's
functionsis invoked, and the arguments are passed to it.
Next the code defines void
write(byte[]
arg0, intstrings
arg1, int arg2).
Formatting,
parsing, and manipulating

public void write(byte[]


arg0,
int
arg2)
throws
Interfacing with
the Javaint
APIs arg1,
and working
with
Java Streams

java.io.IOExceptio

Then it attempts to get the write()


method
from
the Py
instance.
Using Python
and Java
Swing
to create
GUIs

PyObject inst = Py.jfindattr(this,


"write");
Working with SQL and JDBC(TM)
If successful, it invokes thePython
methodand
with
theapplets
following arguments:
Java

if (inst != null)
try
{ contains instructions for downloading and installing the Python
In addition,
the book
inst._jcallexc(new
Object[]
{arg0,
Py.newInteger(arg1),
language and the Java
Development
Kit (JDK).
Terminology, definitions, explanations,
Py.newInteger(arg2)}
); experience.
and numerous code samples make this book a useful learning
}
Whether you are a sophisticated computer user new to programming or a serious
If not successful, it invokes
the superclass's
(OutputStream
write()
method.
application
developer, Python
Programming's)with
the Java(TM)
Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

else super.write(arg0, arg1, arg2);

777

Now that we've explained a little bit of how compiled Python code works underneath, let's create some Java that
uses it.

Java Code That


Uses
a Jythonwith
Class
Python
Programming
the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower
Here'stestOutScreen.java
, which treats OutputScreen like any other

Java class:

public class testOutScreen{


Publisher: Addison Wesley
public static
void
args){
Pub Date: June
28,main(String[]
2002
OutputScreen
os
=
new
OutputScreen();
ISBN: 0-201-61616-5

Table of
Contents

Pages: 640

byte [] bytes = {0,1,2,3,4,5,6,7,8,9,0xa,0xb,0xC} ;


Characterized by ease of use, richness of expression, and concise syntax, Python has
try{ a premier programming language for more than a decade, and is used by
remained
os.write(1);
novices and professionals
alike. In particular, its close relationship to Java(TM) makes
os.write(bytes,
5, 5);
the two languages,
when used in combination,
ideal for Web and distributed enterprise
os.write(bytes);
application development.

}
catch(java.io.IOException
This
tutorial begins with coverage of some of e){
the basics of Python programming. Using
// do something
usefulprogramming
with this
exception
plenty of skill-building
exercises and interactive
sessions,
this book will
} those new to programming develop an understanding of concepts and practical
help
}
techniques. For experienced programmers, the book demonstrates Python's breadth of
}
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
The preceding code needs little explanation, as all it does is create an instance of OutputScreen and call all
three forms of the overloaded
write() method.
compileClass
and run
it, do this:
Python Programming
with the To
Java(TM)
Libraries:
A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
C:\jpybook\chap11\jpywork>javac testOutScreen.java
Fundamental programming
concepts, including statements, expressions,
C:\jpybook\chap11\jpywork>java
testOutScreen
interpreters, and compilers
Python
basics,Java
includingDefault
operators, string
formatting, namespaces, classes, errors,
The
Package
and exceptions
BothOutputScreen
and testOutScreen
in the Java default package, which is okay for
Object-oriented
programmingare
concepts
illustration. However, any experienced Java programmer knows that leaving anything there is impolite.
To put OutputScreen
in its own package use the p option.
File input/output

C:\jpybook\chap11>jythonc
-d p examples.chap11 OutputScreen.py
Python's intrinsic functions
Formatting, parsing, and manipulating strings

Summary

Interfacing with the Java APIs and working with Java Streams

In this chapter, we coveredUsing


how toPython
integrate
Python.
Essentially,
andJava
Javaand
Swing
to create
GUIs Jython makes this integration easy
and, most of the time, transparent. The mappings from Java types to Python types for passing arguments and
returning values from JavaWorking
methods with
are straightforward.
SQL and JDBC(TM)
Jython has added the jarrayPython
module,
allows the creation of the built-in array type that maps to Java
andwhich
Java applets
arrays.jarray allows you to create both empty arrays and arrays initialized with the contents of a sequence. A
Java array is like a homogeneously
withfor
a fixed
length, soand
youinstalling
can use athe
Python
sequence
In addition, thetyped
book Python
containssequence
instructions
downloading
Python
operation on it.
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.

CONTENTS

Whether you are a sophisticated computer user new to programming or a serious


application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
CONTENTS
Web and Enterprise Applications with Jython
By Richard Hightower

Chapter 12. Working


with Java Streams
Publisher: Addison Wesley
Pub Date: June 28, 2002

The Java Way of ISBN:


File Operations
0-201-61616-5
Table of
Text Streams Pages: 640
Contents
Binary Streams: InputStream and OutputStream
Characterized
by ease of use, richness of expression, and concise syntax, Python has
DataInput and
DataOutput
remained a premier programming language for more than a decade, and is used by
The File Class
novices and professionals alike. In particular, its close relationship to Java(TM) makes
The RandomAccessFile
Class
the two languages,
when used in combination, ideal for Web and distributed enterprise
The StreamTokenizer
Class
application development.
Persisting Objects with Java Streams
tutorial
of some of the basics of Python programming. Using
Using Java This
Streams
to begins
Workwith
withcoverage
Memory
plenty of skill-building exercises and interactive programming sessions, this book will
Summary

help those new to programming develop an understanding of concepts and practical


techniques. For experienced programmers, the book demonstrates Python's breadth of
Terms in This Chapter
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
Abstract class
Helper class
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and
Enterprise Applications with Jython covers
important topics such as:
ASCII
Interface
autoexec.bat file
Java networking APIs
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
Buffering
Param eter

Python basics, including operators, string


Caching
Parentformatting,
directory namespaces, classes, errors,
and exceptions
Callable object
Polymorphism
Object-oriented programming concepts
Canonical path
Path separator
File input/output
Chaining
Prefetching
Python's intrinsic functions
Character/byte stream
Separator
Formatting, parsing, and manipulating strings
Class hierarchy
Single inheritance
Interfacing with the Java APIs and working with Java Streams
Concrete class
Slice
Using Python and Java Swing to create GUIs
Current directory
Stream (binary/text)
Working with SQL and JDBC(TM)
Debug utility
Source code
Python and Java applets
Design pattern
Source file
In addition, the book contains instructions for downloading and installing the Python
File descriptor
TokenTerminology, definitions, explanations,
language
and the Java Development Kit (JDK).
and numerous code samples make this book a useful learning experience.
File path (relative/absolute)
Unicode
Whether you are a sophisticated computer user new to programming or a serious
Flag
application
developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.
Streams are the Java programming language's way to support I/O. A stream can represent a file, a network
connection, or the access of a Web site. Learning to deal with Java streams is essential for understanding Java's
networking APIs.

777

Most of the time conversion to and from the Java type system is transparent. When it isn't, this chapter will

demonstrate how to Python


do low-level
type conversion
Programming
with straightforwardly.
the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

As
If One
Publisher:
AddisonWay
Wesley Weren't Bad Enough
Pub Date: June 28, 2002

The joke is that thereISBN:


are always
two ways of doing things in Jython: the Python way and the Java
0-201-61616-5
Table
of
way.
For
example,
if
you
use
Python
to prototype for Java applications, you need to know how

Pages: 640
Contents
Java does it. You also need Java streams to do various forms of Java I/O, such as networking APIs.
Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
The Java Way
ofand
File
Operations
novices
professionals
alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
Interfaces and classes
for dealingdevelopment.
with files and other I/O types are in the java.io package. An interface is a class
application
that contains abstract methods. Classes in java.io form a class hierarchy.
This tutorial begins with coverage of some of the basics of Python programming. Using
The two main class types
are text exercises
oriented (character
streams)
and binary sessions,
oriented (byte
streams).
plentyinofjava.io
skill-building
and interactive
programming
this book
will
Subclasses of the Reader
andnew
Writer
classes aredevelop
text oriented;
those of theofInputStream
and
help those
to programming
an understanding
concepts and practical
OutputStream techniques.
classes are binary
oriented. programmers, the book demonstrates Python's breadth of
For experienced
capabilities and shows the ways that Python interfaces with Java APIs for professional
InputStream and
OutputStream
are abstract; that is, they can't be instantiated directly. To use an
application
development.
abstract class you must subclass it and instantiate the subclass. The subclasses of InputStream and
OutputStream allow
reading of binary
dataJava(TM)
to and from
various
types A
ofTutorial
input and
suchWeb
as byte
Pythonthe
Programming
with the
Class
Libraries:
foroutput
Building
arrays (memory), files,
even network
sockets.with Jython covers important topics such as:
andand
Enterprise
Applications
Streams can be chained to provide extra functionality. For example, you can buffer a FileInputStream by
Fundamental programming
concepts,
including
statements, expressions,
chaining it to a BufferedInputStream
Then you
can chain
the BufferedInputStream
to an
and compilers
ObjectInputStreaminterpreters,
to read in whole
objects at one time. (This is similar to the pickle functionality in
Python.)
Python basics, including operators, string formatting, namespaces, classes, errors,
exceptions
Java 1.1's binary data inputand
streams
are complemented by somewhat equivalent text input streams. The parents of
these classes are the abstract classes Reader and Writer. Having an equivalent set of text-oriented character
Object-oriented
programming
concepts
stream classes allows the conversion
of Unicode
text. Reader
s and Writers, like streams, can be chained
together. For example, you can buffer a FileReader by chaining it to a BufferedReader. (Buffering
File input/output
will be explained shortly.)

Python's intrinsic functions

I/O Classes to Be Covered

Formatting, parsing, and manipulating strings


There are more than thirty I/O classes, not including interfaces and abstract classes. This seems like a lot, but if
Interfacing
with
the Java APIs and
working
with Java Streams
you understand how Reader
,Writer
,InputStream
, and
OutputStream
work, you can easily
understand the rest.
Using Python and Java Swing to create GUIs

Reader and Writer subclasses deal with character streams, that is, text. InputStream and
Working with SQL and JDBC(TM)
OutputStream subclasses deal with binary streams. An easy way to remember this is, if you can read it, use
Reader and Writer; ifPython
you can't,
and OutputStream.
anduse
JavaInputStream
applets
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
For
Beginners:
Streams
and numerous
code samples Understanding
make this book a useful learning
experience.
Whether
are a file.
sophisticated
computer
programming
or read
a serious
Think of a stream
as anyou
abstract
Just as you
can readuser
andnew
writetoto
a file, you can
and write
application
developer,
Programming
theanJava(TM)
Classconnection,
Libraries will
to a stream. You
might use
a stream Python
for reading
and writingwith
with
RS-232 serial
a
give you
intolocation
the power
of aPython
and the
know-how
to put itsotoifwork.
TCP/IP connection,
or insight
a memory
(like
sequence).
A stream
is abstract,
you know
how to read and write to a file, you basically already know how to read and write to a memory
location or an RS-232 serial connection or, for that matter, a Web site. This is the art and magic of
polymorphism.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
Text Streams
Web and Enterprise Applications with Jython
By Richard Hightower

All of the text-oriented classes are derived from Reader and Writer. By understanding them, you'll have a
handle on dealing with Publisher:
their descendents.
Addison Wesley

Writer

Table of
Contents

Pub Date: June 28, 2002


ISBN: 0-201-61616-5
Pages: 640

TheWriter class writes character data to a stream. It has the following methods:
Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
write(c) writes a single character to the text stream
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two
languages,
when used
in combination,
ideal
for Web and distributed enterprise
write(cbuf)
writes
a sequence
of characters
to the text
stream
application development.
write(cbuf, off, len) writes a sequence of characters to the text stream starting at the
tutorial
begins with
coverage
some of the basics of Python programming. Using
offset into the This
stream
and copying
to len
in the of
buffer
plenty of skill-building exercises and interactive programming sessions, this book will
help
programming
develop
write(str)
those
writesnew
outto
a string
to the text
streaman understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
write(str,
off, and
len)
writes
out athat
string
frominterfaces
the givenwith
offset
to the
given
length
capabilities
shows
the ways
Python
Java
APIs
for professional
application development.
close() closes the text stream
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
flush()and
flushes
the content
of the text
stream;
used
if theimportant
stream supports
BufferedOutput
Enterprise
Applications
with
Jython
covers
topics such
as:

Writer is the superclass of all character output streams, for example, FileWriter,
BufferedWriter,CharArrayWriter
,OutputStreamWriter
, and PrintWriter
Fundamental programming
concepts, including statements,
expressions, .
interpreters, and compilers

Reader

Python basics, including operators, string formatting, namespaces, classes, errors,


and exceptions
TheReader class reads data from a stream. Reader is the superclass of all character input streams. It has the
following methods:
Object-oriented programming concepts
File input/output

read() reads in a single character


Python's intrinsic functions

read(cbuf) reads in a sequence of characters


Formatting, parsing, and manipulating strings

read(cbuf, iOff, iLen) reads from the current position in the file into the sequence at the
given offset

Interfacing with the Java APIs and working with Java Streams

ready() determines
the buffer
data
UsingifPython
and has
Javainput
Swing
to ready
create GUIs
mark(int readAheadLimit)
sets
the read-ahead buffer size
Working with SQL
and
JDBC(TM)
markSupported()
returns
true
if the mark() method is supported
Python
and Java
applets
skip() skips
a certainthe
number
of characters
ahead in
text input stream
In addition,
book contains
instructions
forthe
downloading
and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,

reset()and
moves the file pointer to the marked position
numerous code samples make this book a useful learning experience.

close()Whether
closes the file
you are a sophisticated computer user new to programming or a serious
Pythonor
Programming
with the
Java(TM)
Class
will
I can't show you anyapplication
examples ofdeveloper,
using Reader
Writer because
they're
abstract
andLibraries
can't be instantiated
give you insight into the power of Python and the know-how to put it to work.
on their own. However, I can show examples of their subclasses, FileReader and FileWriter, which are concrete.
As an exercise, look up Reader and Writer in the Java API documentation, and compare their Pythonfriendly method definitions to the official Java versions. Notice the conversion from one type to another.

777

FileReader and
FileWriter
Python
Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
Richard Hightower
FileReader andBy
FileWriter
read and write text files. They have

the same methods their base classes

have as well as the following constructor methods.


Publisher: Addison Wesley

FileReader:

Pub Date: June 28, 2002

ISBN: 0-201-61616-5
Table of
Pages: 640
Contents
__init__(strFilename) opens

the file specified by the string ( strFilename)

Characterized
by ease
of use,
richness
__init__(File)
opens
the file
specified
by of
theexpression,
file object and concise syntax, Python has

remained a premier programming language for more than a decade, and is used by
novices
professionals
alike. In
its close relationship to Java(TM) makes
__init__(fd)
and
opens
the file specified
byparticular,
the file descriptor
the two languages, when used in combination, ideal for Web and distributed enterprise
FileWriter:
application development.
This tutorial begins with coverage of some of the basics of Python programming. Using

__init__(strFilename)
exercises
opens theand
file interactive
specified byprogramming
the string ( strFilename
) will
plenty of skill-building
sessions, this book
help those new to programming develop an understanding of concepts and practical

__init__(strFilename,
bAppend) same as above, but optionally opens the file in append
techniques. For experienced programmers, the book demonstrates Python's breadth of
mode

capabilities and shows the ways that Python interfaces with Java APIs for professional
application
__init__(File)
development.
opens the file specified by the file object
PythonProgramming
the Java(TM)
Class
Libraries: A Tutorial for Building Web
__init__(fd)
opens the filewith
specified
by the file
descriptor

and Enterprise Applications with Jython covers important topics such as:
As an exercise, look up FileReader and FileWriter in the Java API documentation. Then modify the
address book application from
Chapter 8programming
to use these classes.
Fundamental
concepts, including statements, expressions,
interpreters, and compilers
Creating a File with FileWriter
Python basics, including operators, string formatting, namespaces, classes, errors,
The following interactive session
creates a file with FileWriter and writes some text to it. (Follow along.)
and exceptions
Import the FileWriterObject-oriented
class from the java.io
package.
programming
concepts

>>> from java.io File


import
FileWriter
input/output
Create an instance of it.

Python's intrinsic functions

>>> fw = FileWriter("c:\\dat\\File.txt")
Formatting, parsing, and manipulating strings
Write a single character to Interfacing
the output character
stream.
with the Java
APIs and working with Java Streams

>>> fw.write('w')Using Python and Java Swing to create GUIs


Write out a string.

Working with SQL and JDBC(TM)

>>> fw.write("\r\nthis
string")
Python andis
Javaaapplets
Write out a sequenceInofaddition,
characters.
the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
>>> characters
= ('\r','\n','a','b','c')
and numerous
code samples make this book a useful learning experience.

>>> fw.write(characters)
Close the file.

Whether you are a sophisticated computer user new to programming or a serious


application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

>>> fw.close()

777

Here's what the file we just created, called c:\dat\file.txt, looks like. You can open it with Notepad or any other
text editor.

w
Python Programming with the Java Class Libraries: A Tutorial for Building
this is a string
Web and Enterprise Applications with Jython
abc
By Richard Hightower
Publisher: Addison Wesley

Finding the File Length

Pub Date: June 28, 2002

Table of
You can use
Contents

ISBN: 0-201-61616-5

a java.io
file to640
see the length of c:\dat\file.txt. It should be 22 bytes.
Pages:

>>> from Characterized


java.io by
import
File
ease of use,
richness of expression, and concise syntax, Python has
>>> f
= File("c:\\dat\\File.txt")
remained
a premier programming language for more than a decade, and is used by
>>> file.length()
novices and professionals alike. In particular, its close relationship to Java(TM) makes
22L f
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
Don't worry too much about what the File class does; we'll cover it later. For now, just think of it
as a way to specify
a file and
get its
properties.
This tutorial
begins
with
coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
those new
to programming develop an understanding of concepts and practical
Reopenc:\dat\file.txt help
in append
mode.
techniques. For experienced programmers, the book demonstrates Python's breadth of
>>> fw = FileWriter('c:\\dat\\File.txt',
1)
capabilities and shows the ways that Python interfaces
with Java APIs for professional
application development.
Append some text.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
>>> fw.write("\r\nAnother
String
appended
to thetopics
File")
and Enterprise Applications
with Jython
covers important
such as:

>>> fw.close()

We open the file in appendFundamental


mode by passing
a true (concepts,
1) to the second
parameter
of the
FileWriter
programming
including
statements,
expressions,
constructor. This means that
we
want
to
append
text.
You
can
see
from
the
following
example
(c:\dat\file.txt)
interpreters, and compilers
that the text has been added.
Python basics, including operators, string formatting, namespaces, classes, errors,
w
and exceptions

this is a string
abc
Object-oriented programming concepts
Another String appended to the File
File input/output
If we now write to the file and don't open it in append mode, all of the old text will be deleted.
Python's intrinsic functions

>>>
>>>
>>>
>>>
32L

fw = FileWriter(File)
Formatting,
and manipulating
strings
fw.write("Oops
whereparsing,
is all
the other
text")
fw.close()
f.length() Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs

Look at the file with a text editor. It should have text only in the last write statement.
Working with SQL and JDBC(TM)
By the way, the concepts just covered for working with FileWriter aren't much different from those for
Python and Java applets
working with the Python file object.

In addition, the book contains instructions for downloading and installing the Python
Reading a File with
FileReader
language
and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Now it's FileReader's turn with an interactive session. We'll open c:\dat\file\txt and read the text we wrote
Whether
to it with FileWriter
. you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
Import the FileReader
from
thethe
java.io
give youclass
insight
into
powerpackage.
of Python and the know-how to put it to work.

>>> from java.io import FileReader


>>> File_Reader = FileReader("C:\\dat\\File.txt")

777

The tricky part is thatPython


the read()
method expects
you
to passClass
it a chars
array
that it canfor
fillBuilding
in, but the
Programming
with the
Java
Libraries:
A Tutorial
closest thing in Python
to and
a Java
array is a sequence
or list,
andJython
neither is close enough. So Jython has added a
Web
Enterprise
Applications
with
helper class, called PyArray
that passes primitive arrays to Java methods (see Chapter 11).
By Richard ,Hightower
Import the zeros() function
from the jarray module.
Publisher: Addison Wesley
Date: June 28, 2002
>>> from jarrayPubimport
zeros
Table of
Usezeros()
Contents to

ISBN: 0-201-61616-5

create

Pages: 640 .
a PyArray

>>> chars = zeros(4,


Characterized 'c')
by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
Print the chars array
to theand
screen.
novices
professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
>>> chars
application development.

array(['\x0', '\x0', '\x0', '\x0'], char)

This tutorial begins with coverage of some of the basics of Python programming. Using
The first argument toplenty
zeros()
tells it howexercises
big we want
our array. The
second argument
of skill-building
and interactive
programming
sessions,tells
thiszeros()
book will that
we want our array tohelp
be ofthose
type new
char
.
Now
zeros()
creates
an
array
in
which
all
of
the
values
are zeros.
to programming develop an understanding of concepts and practical
When we call Filetechniques.
_Reader.For
read
,
the
read()
method
fills
in
the
empty
slots
with
characters
from
experienced programmers, the book demonstrates Python's breadth
of the
file.
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
Here's our call to the read() method, which should read the first four letters of the file.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web

>>> File_Reader.read(chars)
and Enterprise Applications with Jython covers important topics such as:
4

As you can see, chars contains


the firstprogramming
four letters inconcepts,
our file, including
'O','o'statements,
,'p', and 's'
.
Fundamental
expressions,

interpreters, and compilers

>>> chars
array(['O', 'o', Python
'p',basics,
's'],
char)
including
operators, string formatting, namespaces, classes, errors,
and exceptions
This is nice but what we really want is a string object, 'Oops'. For this we need PyArray, which we can use
anywhere a sequence is suitable,
such as theprogramming
Python classconcepts
library.
Object-oriented
The Python string module File
has methods
for doing special things with strings. One method, joinfields(),
input/output
combines strings in a sequence to form a string object. Let's use joinfields() to convert chars to a
string.
Python's intrinsic functions
Import the string module. Formatting, parsing, and manipulating strings

>>> import stringInterfacing with the Java APIs and working with Java Streams
Use joinfields() to Using
turn the
chars
a Python
string.
Python
andarray
Javainto
Swing
to create
GUIs

>>> first_word = Working


string.joinfields(chars,
"")
with SQL and JDBC(TM)
Print the value of first_word
to the
screen.
Python and
Java
applets

>>> first_word
In addition, the book contains instructions for downloading and installing the Python
'Oops'
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Notice that the second argument to joinfields() specifies the separator we want for the fields. Since we
don't want any separator,
we pass
string. computer user new to programming or a serious
Whether
you an
are empty
a sophisticated
application developer, Python Programming with the Java(TM) Class Libraries will
Let's recap what we've
learned
to readinto
in the
once.
give
you insight
the whole
power c:\dat\file.txt
of Python andfile
theatknow-how
to put it to work.

>>> from jarray import zeros


# import the zeros to create an array of
primitives
>>> from java.io import FileReader, File # import the File to get the length
of the file

777

>>> from string


import
joinfields
# Class
import
the Ajoinfields
to convert arrays
Python
Programming
with the Java
Libraries:
Tutorial for Building
to strings
Web and Enterprise Applications with Jython
>>> file = File("c:\\dat\\file.txt")
# create a java.io.File instance
By Richard Hightower
>>> chars = zeros(file.length(), 'c')
# create an array to hold the
contents ofPublisher:
file.txt
Addison Wesley
>>> file_ReaderPub=Date:
FileReader(file)
# create a FileReader instance to read the
June 28, 2002
file >>> >>> ISBN:
file_Reader.read(chars)
# Read in the whole file
0-201-61616-5
Table
of
32

Pages: 640
Contents

That took only eight steps. Let's see the same thing with the Python file object.
Characterized by ease of use, richness of expression, and concise syntax, Python has
remained
a premier programming language for more than a decade,
and isthe
used by
>>> python_file
= open("c:\\dat\\file.txt","r")
# open
file
novices
and
professionals
alike.
In
particular,
its
close
relationship
to
Java(TM)
makes of the file
>>> str = python_file.read()
# read the contents
>>> print strthe two languages, when used in combination, ideal for Web and distributed enterprise
development.
Oops where isapplication
all the
other text

This
tutorial
begins with
coverage of some
of thenow
basics
of Python
programming.
What took eight steps
with
the java.io
.FileWriter
instance
takes
two steps.
Which one Using
would you
plenty
of
skill-building
exercises
and
interactive
programming
sessions,
this book will
rather work with?
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
BufferedReader
and BufferedWriter
capabilities
and shows the ways that Python interfaces with Java APIs for professional
application development.
TheBufferedReader class provides input buffering to the Reader stream. The BufferedWriter
class provides outputPython
buffering
to the Writer
stream.
Input Class
buffering
consists
prefetching
data and
caching
Programming
with the
Java(TM)
Libraries:
A of
Tutorial
for Building
Web
it in a memory queueand
so that,
for example,
not every
to the
read()
method
equates
Enterprise
Applications
withcall
Jython
covers
important
topics
suchtoas:a read operation on
the physical I/O. Output buffering applies writes to a memory image that is periodically written out to a character
stream. You want buffering support for input and output streams, especially large ones, to gain speed and
Fundamental programming concepts, including statements, expressions,
efficiency.
interpreters, and compilers
BufferedReader and BufferedWriter have all of the methods that Reader and Writer have, as
Python basics, including operators, string formatting, namespaces, classes, errors,
well as the following:
and exceptions
BufferedWriter:
Object-oriented programming concepts
File input/output
__init__ (Writer_in)
creates a BufferedWriter instance with the specified output
stream

Python's intrinsic functions

__init__(Writer_in, iBufSize) same as above but specifies the size of the buffer
Formatting, parsing, and manipulating strings

newLine() writes a newline character to the output stream

Interfacing with the Java APIs and working with Java Streams

BufferedReader:

Using Python and Java Swing to create GUIs

Working with
andaJDBC(TM)
__init__ (Reader_in)
SQL
creates
BufferedReader instance with the specified input
stream

Python and Java applets

__init__(Reader_in, iBufSize) same as above but specifies the size of the buffer
In addition, the book contains instructions for downloading and installing the Python

language
and
Java
Kit (JDK).
readLine()
reads
in the
a line
of Development
text from the input
streamTerminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Using the Buffering Classes
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
Let's have a short interactive session showing how to use our buffering classes. We'll also cover the
give you insight into the power of Python and the know-how to put it to work.
newLine() and readLine() methods.

777

Import the BufferedReader and BufferedWriter classes and the FileReader and
FileWriter classes.

>>> from java.io


BufferedReader,
BufferedWriter,
FileReader,
FileWrite
Pythonimport
Programming
with the Java Class
Libraries: A Tutorial for
Building
Web and Enterprise Applications with Jython

Create a FileWriter
instance
that creates a file called c:\dat\buf_file.txt.
By Richard
Hightower

>>> file_out = FileWriter("c:\\dat\\buf_file.txt")


Publisher: Addison Wesley

Pub Date:
June 28,buffer_out
2002
Create a BufferedWriter
instance,
, passing it as an argument to the
ISBN: 0-201-61616-5
BufferedWriter
constructor.
Table of

Contents

Pages: 640

>>> buffer_out = BufferedWriter(File_out)


Characterized by ease of use, richness of expression, and concise syntax, Python has
Write three lines of text
to the afile
using programming
write() to language
write the for
characters
andathen
newLine()
remained
premier
more than
decade,
and is used to
bywrite the
platform-specific newline
characters.
novices
and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
>>> buffer_out.write("Line
application development.1"); buffer_out.newLine()

>>> buffer_out.write("Line 2"); buffer_out.newLine()


>>> buffer_out.write("Line
buffer_out.newLine()
This tutorial begins with3");
coverage
of some of the basics of Python programming. Using

plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
>>> buffer_out.close()
capabilities and shows the ways that Python interfaces with Java APIs for professional
application
This code demonstrates
chainingdevelopment.
a BufferedWriter to a FileWriter, which adds buffering to file
Close the stream.

output.

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and
Enterprise Applications
with
covers
topics such as:
The next session uses
FileReader
to open the
fileJython
we created
inimportant
the last example.
Create a FileReader instance, and pass it to the BufferedReader constructor to create a
Fundamental programming concepts, including statements, expressions,
BufferedReader instance.
interpreters, and compilers

>>> file_in = BufferedReader(FileReader("c:\\dat\\buf_File.txt"))

Python basics, including operators, string formatting, namespaces, classes, errors,


andwith
exceptions
Read in all three lines at once
three method calls to readLine().
programming concepts
>>> line1, line2,Object-oriented
line3 = file_in.readLine(),
file_in.readLine(),
file_in.readLine()
File input/output

Print all three lines at once.


Python's intrinsic functions

>>> print line1; print line2; print line3


Formatting, parsing, and manipulating strings
Line 1
Line 2
Interfacing with the Java APIs and working with Java Streams
Line 3
Using Python and Java Swing to create GUIs
You may be wondering why there's a newLine() function in BufferedWriter. It's there because it
knows how to represent a newline
onand
whatever
operating system you happen to be writing your code
Workingcharacter
with SQL
JDBC(TM)
for. (We used "\r\n" in our FileWriter example, which won't work on UNIX or Mac.)
Python and Java applets

PrintWriter

In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
PrintWriter provides
a print() and a println() function for all primitive types. These functions
and numerous code samples make this book a useful learning experience.
convert primitive types to characters and then write them to the output stream. PrintWriter has all of
write() methods,Whether
as well as
youthese:
are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
youout
insight
into data
the power
of an
Python
and
the know-how
to put
print()give
writes
primitive
types to
output
stream
(as readable
text)it to work.

println() same as above, but adds a newline character to the ouput

777

In the next example, you'll see how to use PrintWriter, how to chain output streams together, and how to work

with Java primitive types.


Python Programming
Import the classes

with the Java Class Libraries: A Tutorial for Building


Web and Enterprise Applications with Jython
needed.
By Richard Hightower

>>> from java.io import PrintWriter, FileWriter, BufferedWriter


Publisher: Addison Wesley

Pub by
Date:
Juneit28,
2002
Create a PrintWriter
passing
a new
instance of BufferedWriter, which is created from a new
ISBN:
0-201-61616-5
instance
of
FileWriter
.
Table of

Contents

Pages: 640

>>> out = PrintWriter(BufferedWriter(FileWriter("pr.txt")))


Characterized by ease of use, richness of expression, and concise syntax, Python has
Write three strings toremained
a file using
println()
.
a premier
programming
language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
>>> out.println("Line1")
the two languages, when used in combination, ideal for Web and distributed enterprise
>>> out.println("Line2")
application development.

>>> out.println("Line3")

This tutorial begins with coverage of some of the basics of Python programming. Using
Use println() toplenty
writeof
a Python
Double
objectand
andinteractive
a Python Integer
object
to a file.
skill-building
exercises
programming
sessions,
this book will
help those new to programming develop an understanding of concepts and practical

>>> out.println(4.4)
techniques. For experienced programmers, the book demonstrates Python's breadth of
>>> out.println(5)

capabilities and shows the ways that Python interfaces with Java APIs for professional
application
development.
Write a Java Boolean
to the file.
Python Programming
the Java(TM) Class Libraries: A Tutorial for Building Web
>>> from java.lang
import with
Boolean
and
Enterprise
Applications
with Jython covers important topics such as:
>>> out.println(Boolean(1))
>>> out.println(Boolean("true"))
Fundamental programming concepts, including statements, expressions,
Write a Java Byte to the file.
interpreters, and compilers

>>> from java.lang import Byte


Python basics, including operators, string formatting, namespaces, classes, errors,
>>> out.println(Byte(1))
and exceptions

Show how print() works.


Object-oriented programming concepts

>>> out.print("Line 9")


File input/output
>>> out.print("still line 9")
>>> out.close() Python's intrinsic functions
(It also works with primitive
types.) parsing, and manipulating strings
Formatting,
Now you know how to chain
stream classes
to add
functionality
youwith
want.
TheStreams
out instance, for example,
Interfacing
with the
Javathe
APIs
and working
Java
can write to files from FileWriter, work with output buffering from BufferedWriter, and work with
primitive types from PrintWriter
way,
the technique
of chaining Writer stream classes is known
Using Python. By
andthe
Java
Swing
to create GUIs
as the Decorator design pattern. To learn more about if read Design Patterns (Gamma et al., [1995]).
Working with SQL and JDBC(TM)

Binary Streams:Python
InputStream
and Java applets and OutputStream
theReader
book contains
instructions forisdownloading
installing
the Python
InputStream isIn
theaddition,
analog of
;OutputStream
the analog ofand
Writer
. Their
methods are
listed here.

language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.

InputStream:

Whether you are a sophisticated computer user new to programming or a serious


application developer, Python Programming with the Java(TM) Class Libraries will
read(byte_sequence)
reads
a sequence
of bytes
returns the to
actual
read
give you insight into
the power
of Python
and and
the know-how
put itbytes
to work.

read(byte_sequence, off, len) same as above but allows you to set the slice for the

777

sequence; returns the number of actual bytes read

read() reads one byte of data from the input stream

Python Programming with the Java Class Libraries: A Tutorial for Building

skip(n)Web
skips to a given offset in the file
and Enterprise Applications with Jython
By Richard Hightower

close() closes the stream

Publisher:
reset() moves
the fileAddison
pointerWesley
to the marked position
Pub Date: June 28, 2002

mark(iReadlimit)
marks the file pointer
ISBN:0-201-61616-5

Table of
Pages: 640
Contents
available() returns the number

of bytes available that can be read without blocking (similar to


theReader Characterized
class'sready()
method)
by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
OutputStream :
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
close() application development.

tutorial
begins that
withis,coverage
of output
some of
the basics
of Python
programming.
Using
flush()This
flushes
the buffer,
forces the
buffer
to be written
to the
output stream
plenty of skill-building exercises and interactive programming sessions, this book will

write(b)
writes
to the output
streaman understanding of concepts and practical
help
thosea single
new tobyte
programming
develop
techniques. For experienced programmers, the book demonstrates Python's breadth of

write(byte_sequence)
writes
a sequence
of bytes
to the with
output
stream
capabilities and shows
the ways
that Python
interfaces
Java
APIs for professional
application development.

write(byte_sequence, off, len) same as above, but specifies the slice


Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and and
Enterprise
Applications with Jython covers important topics such as:
FileInputStream
FileOutputStream

FileInputStream and
FileOutputStream extend InputStream and OutputStream,
Fundamental programming concepts, including statements, expressions,
respectively. They are the analogs to FileReader and FileWriter. Here are their methods.
interpreters, and compilers
FileInputStream:

Python basics, including operators, string formatting, namespaces, classes, errors,


and exceptions
__init__(strFilename) opens the file specified by the string (strFilename)
Object-oriented programming concepts
__init__(File) opens the file specified by the file object
File input/output
__init__(fd) opens the file specified by the file descriptor
Python's intrinsic functions

FileOutputStream:

Formatting, parsing, and manipulating strings

Interfacing with
Javathe
APIs
working
withstring
Java (Streams
__init__(strFilename)
the
opens
file and
specified
by the
strFilename)
Using Python and
Java Swingtosame
create
__init__(strFilename,
bAppend)
asGUIs
above, but optionally opens the file in append
mode

Working with SQL and JDBC(TM)

__init__(File) opens the file specified by the file object

Python and Java applets


__init__(fd) opens the file specified by the file descriptor
In addition, the book contains instructions for downloading and installing the Python
and the
Java Development Kitand
(JDK).
Terminology, definitions,
Reading and writinglanguage
to a file with
FileInputStream
FileOutputStream
are explanations,
a lot like reading
and
numerous
code
samples
make
this
book
a
useful
learning
experience.
and writing to a file with FileReader and FileWriter. That being the case, I'm omitting much of the
detail in the following example (OutputStream 1.py) to avoid repetition.
Whether you are a sophisticated computer user new to programming or a serious
Python Programming withclass
the Java(TM)
Libraries
will package
# First weapplication
importdeveloper,
the FileOutputStream
fromClass
the
java.io
give
you
insight
into
the
power
of
Python
and
the
know-how
to
put
it
to
work.
from java.io import FileOutputStream

from jarray import array

777

# Next create an instance of the FileOutputStream


out = FileOutputStream("c:\\dat\\file.bin")

Python Programming with the Java Class Libraries: A Tutorial for Building

# Now write
a byte to the output binary stream
Web and Enterprise Applications with Jython
out.write(1) ByRichard Hightower

# Now write Publisher:


some more
bytes to the binary stream
Addison Wesley
out.write([2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])
Pub Date: June 28, 2002

ISBN: 0-201-61616-5

#Table
Next
of write out a string
Pages: 640
Contents
#out.write("\r\nthis
is a string") #Jython converts this automatically

Characterized by ease of use, richness of expression, and concise syntax, Python has

# Here is the hard way


remained a premier programming language for more than a decade, and is used by
str = "\r\nthis is a string"

novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
# First convert every character in the string into its ASCII equivalent
application development.

seq = map(ord, str)

This tutorial begins with coverage of some of the basics of Python programming. Using

# Now convert
sequence
into
Java programming
array of sessions,
the primitive
plenty ofthe
skill-building
exercises
and a
interactive
this book will type byte
bytes = array(seq,
'b')
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of

# Now write
out this
string
file
as with
follows
capabilities
and shows
the waysto
thatthe
Python
interfaces
Java APIs for professional
out.write(bytes)
application development.
out.close() Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
The code above may seem familiar at first, but as you examine it you'll notice a couple of strange things. First,
sincewrite() works only with bytes and byte arrays, we have to use the jarray module again. Second, Jython
converts a string into a byteFundamental
array automatically,
but if the
class has
two write()
methodsone
programming
concepts,
including
statements,
expressions, that takes a
andhave
compilers
string and one that takes a interpreters,
byte arraywe
to do some extra work to make sure that the correct method is
called. Thus, we have to convert the string to a byte array if we want the byte array method.
Python basics, including operators, string formatting, namespaces, classes, errors,
andord()
exceptions
Using the intrinsic functions
and map(), we'll see how to manually convert the string into a byte array
before passing it to the write() method.
Object-oriented programming concepts
ord()

File input/output

Remember from Chapter 9Python's


that the ord()
intrinsic function
functionstakes a single character from a string and converts it to its
ASCII equivalent (i.e., the number representation of the character stored in the file). Let's work with an
interactive example.
Formatting, parsing, and manipulating strings
Convert"A","B", and "C"
to ASCII.with the Java APIs and working with Java Streams
Interfacing

>>> ord("A"), ord("B"),


Using Pythonord("C")
and Java Swing to create GUIs
(65, 66, 67)
Working with SQL and JDBC(TM)
Convert"a","b", and "c" to ASCII.
Python and Java applets

>>> ord("a"), ord("b"), ord("c")


(97, 98, 99) In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
Figure the distance from
"a" to "z"
from "A"
"Z"
. a useful learning experience.
and numerous
codeand
samples
maketothis
book

>>> ord("z") Whether


- ord("a")
you are a sophisticated computer user new to programming or a serious
25
application developer, Python Programming with the Java(TM) Class Libraries will
>>> ord("Z") give
- ord("A")
you insight into the power of Python and the know-how to put it to work.
25
map()

777

The built-in map()Python


functionProgramming
deals with sequences,
asJava
we alsoClass
learned
in Chapter
9. It takesfor
two
arguments:
with the
Libraries:
A Tutorial
Building
first, a callable objectWeb
suchand
as aEnterprise
function or Applications
a method; second,
type of sequence like a string, list, or tuple.
withaJython
map() executes theBycallable
against every item in the sequence and then returns a list of the results.
Richardobject
Hightower
Thus,
Publisher: Addison Wesley

>>> [ord("a"), Pub


ord("b"),
ord("c"), ord("d")]
Date: June 28, 2002
[97, 98, 99, 100]

is the

ISBN: 0-201-61616-5

Table of
same as
Contents

Pages: 640

Characterized by ease of use, richness of expression, and concise syntax, Python has
>>> map(ord,"abcd")
[97, 98, 99, remained
100] a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
Once we have a sequence,
can convert
it into
array using ideal
the array()
function
from enterprise
jarray (see the
the twowe
languages,
when
useda byte
in combination,
for Web and
distributed
section on FileReader
).array()
takes two arguments: the first is a sequence and the second is a
application
development.
character representing the Java primitive type you want the array to be. (This is an extra step; Jython
This
with
coverage
of some of the basics of Python programming. Using
automatically converts
antutorial
integer begins
sequence
into
a byte array.)
plenty of skill-building exercises and interactive programming sessions, this book will
new
to programming develop an understanding of concepts and practical
This code creates anhelp
arraythose
full of
bytes:
techniques. For experienced programmers, the book demonstrates Python's breadth of
>>> from jarray
import
array
capabilities
and shows
the ways that Python interfaces with Java APIs for professional
>>> seq = map(ord,
"abcd")
application development.

>>> array(seq, 'b')


array([97, 98,
99,
100], byte)
Python
Programming
with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
The Debug Utility
Fundamental programming concepts, including statements, expressions,
Of course, having both binary data and text data makes the file difficult to read. We can at least read the text part
interpreters, and compilers
with a text editor, but besides the text there's only a lot of black boxes where our binary data should be. To see
the binary contents of the file,
we need
another
program.
Python
basics,
including
operators, string formatting, namespaces, classes, errors,
and exceptions
If you're running some variation of Windows or DOS, you can use the debug utility, C:\dat.debug\file.bin. As
shown below, the -d command
dumps some
of the file toconcepts
the screen, and the -q command quits the program.
Object-oriented
programming
You have to enter the commands the way you enter statements in Jython.
File input/output

C:\dat>debug
-d
0E7F:0100 01
0E7F:0110 0D
0E7F:0120 6E
0E7F:0130 49
0E7F:0140 DB
0E7F:0150 02
0E7F:0160 4E
0E7F:0170 89
-q

File.bin

Python's intrinsic functions

02
0A
67
AC
F9
3C
32
0E

03 04 05 06 07 08-09 0A 0B 0C 0D 0E 0F
Formatting,
and69-73
manipulating
74
68 69parsing,
73 20
20 strings
61 20 73 74 72
2B DE 59 03 CB 8B-D6 C6 06 BB DB 00 E3
Interfacing
Java49-46
APIs andFE
working
with DB
Java EB
Streams
E8
D9 F6with
74the08
06 BB
EF
75 04 FE 06 17 D9-3C 3F 75 05 80 0E 1B
Using
to create
GUIs06 02 D3 75
2A
75Python
05 and
80 Java
0E Swing
1B-D9
02 3A
C0
86 04 46 3C 0D-75 02 88 04 89 36 D9
Working with SQL and JDBC(TM)
D7 D7 C3 BE BC DB-8B 4C 05 8B 74 09 E8

10
69
31
E8
D9
C9
D7
08

................
..this is a stri
ng+.Y..........1
I....t.IF.......
..u.....<?u.....
.<*u......:...u.
N2...F<.u....6..
.........L..t...

Python and Java applets

What you have is three


main columns
of data.
To the
far left is for
the downloading
position of theand
fileinstalling
in hexadecimal
notation. In
In addition,
the book
contains
instructions
the Python
the middle is the value
of
the
binary
data,
also
in
hexadecimal
notation,
and
to
the
far
right
is
the
data's
ASCII
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
equivalent.
and numerous code samples make this book a useful learning experience.

Whether you are a sophisticated computer user new to programming or a serious


application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

Hexadecimal

Addison
WesleyThis list shows some decimal numbers and their
Hexadecimal is aPublisher:
base 16 number
system.
Pub Date: June 28, 2002
hexadecimal equivalents:

Table of
Decimal
Contents

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

ISBN: 0-201-61616-5

Hexadecimal
1
2
Characterized by ease of use, richness
of expression, and concise syntax, Python has
remained a premier programming3language for more than a decade, and is used by
novices and professionals alike. In4 particular, its close relationship to Java(TM) makes
the two languages, when used in combination,
ideal for Web and distributed enterprise
5
application development.
6
7
This tutorial begins with coverage of some of the basics of Python programming. Using
8
plenty of skill-building exercises and interactive programming sessions, this book will
9
help those new to programming develop an understanding of concepts and practical
A
techniques. For experienced programmers,
the book demonstrates Python's breadth of
B Python interfaces with Java APIs for professional
capabilities and shows the ways that
C
application development.
D
Python Programming with the Java(TM)
Class Libraries: A Tutorial for Building Web
E
and Enterprise Applications with FJython covers important topics such as:
Pages: 640

Here's the first line of binary


data. Everyprogramming
two digits represent
a single
byte. statements, expressions,
Fundamental
concepts,
including
interpreters, and compilers

01 02 03 04 05 06 07 08-09 0A 0B 0C 0D 0E 0F 10

Python basics, including operators, string formatting, namespaces, classes, errors,


We wrote it the following calls:
and exceptions

out.write(1)

Object-oriented programming concepts

out.write([2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])
File input/output
You can see that the bytes in
the fileintrinsic
increasefunctions
from 1 to 16 in hexadecimal.
Python's
Let's see how to read the file
back in byparsing,
readingand
in the
string.
Formatting,
manipulating
strings
ImportFileInputStream
, and then
an instance
refers to
c:\dat\file.bin.
Interfacing
withcreate
the Java
APIs andthat
working
with
Java Streams

>>> from java.io Using


import
PythonFileInputStream
and Java Swing to create GUIs
>>> file = FileInputStream("c:\\dat\\file.bin")
Working with SQL and JDBC(TM)
Import the jarray buffer to create binary input buffers. The 'b' flag, the second argument to the zeros()
function call, signifies a byte
array.and
We'll
useapplets
input_buffer to read in the first 16 bytes of data.
Python
Java
Import the zeros()
the jarray
module.
In function
addition, from
the book
contains
instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
>>> from jarray
importcode
zeros
and numerous
samples make this book a useful learning experience.
Create a byte input buffer
withyou
zeros()
.
Whether
are a sophisticated
computer user new to programming or a serious

application developer, Python Programming with the Java(TM) Class Libraries will

>>> input_buffer
= zeros(16, 'b')
give you insight into the power of Python and the know-how to put it to work.

Read in the first 16 bytes to the buffer with the read() method, which returns the number of bytes read in.

777

>>> file.read(input_buffer)
16

Python Programming
Print the array of bytes
buffered.

with the Java Class Libraries: A Tutorial for Building


Web and Enterprise Applications with Jython
By Richard Hightower

>>> input_buffer
array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], byte)
Publisher: Addison Wesley

Create a small buffer toPub


readDate:
"\r\n"
June .28, 2002
ISBN: 0-201-61616-5

of
>>> Table
input_buffer
= zeros
(2,'b')
Pages:
640
>>> Contents
file.read(input_buffer)
2
Characterized by ease of use, richness of expression, and concise syntax, Python has

remained a premier programming language for more than a decade, and is used by
Read in "this is a string" from the file.
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two =languages,
when used in combination,
ideal in
for Web
distributed
enterprise
>>> input_buffer
zeros(16,'b')
#read
theand
bytes
for
the string
application
development.
>>> file.read(input_buffer)

16

This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
Since we read this in as bytes, the code shows the ASCII equivalents for the characters we want instead of the
help those new to programming develop an understanding of concepts and practical
actual characters of the string. We need to convert this byte array into a string sequence.
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
>>> input_buffer
application
development.
array([116, 104,
105,
115, 32, 105, 115, 32, 97, 32, 115, 116, 114,

105, 110, 103], byte)

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
Applications
with Jython
important
topics
such time
as: we append the
To do the conversionand
weEnterprise
create a sequence
and iterate
throughcovers
the byte
array. At
the same
results of executing the chr() built-in function against each byte array item. chr() is the reverse of ord();
it converts a number (ASCII
code) into aprogramming
character (i.e.,concepts,
a string with
one item).
Fundamental
including
statements, expressions,
interpreters,
and compilers
Lastly, we convert the sequence
into a string
with a call to string.joinfields().
Python basics, including operators,
string formatting,
namespaces,
classes, errors,
>>> seq = []
# create
an empty
sequence
and
exceptions
>>> for num in input_buffer:
# for every number in the input_buffer
...
seq.append(chr(num))
# append the results of chr(num) to the
Object-oriented programming concepts
# sequence
...
File input/output
>>> seq
# show what the sequence contains
['t', 'h', 'i',
's',
' functions
', 'i', 's', ' ', 'a', ' ', 's', 't', 'r', 'i',
Python's
intrinsic
'n', 'g']
Formatting, parsing, and manipulating strings

>>> import string


# import the string module
Interfacing with the Java APIs
and#working
with the
Java Streams
>>> str = string.joinfields(seq,
"")
create
string from the sequence
>>> print str
# print out the string
Using Python and Java Swing to create GUIs

Of course, a more Pythonesque way to convert the byte array into a string is with the built-in map() function.
Working with SQL and JDBC(TM)

>>> str = string.joinfields(map(chr,input_buffer),"")


Python and Java applets
>>> print str
this is a string
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.

map()can be very useful; it takes one line of code to accomplish what previously took four.

BufferedInputStream
and
Whether you
are aBufferedOutputStream
sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight
into the power of Python and theprovide
know-how
to putkind
it to of
work.
BufferedInputStream
and BufferedOutputStream
the same
support to
InputStream and OutputStream that BufferedReader and BufferedWriter provide to
Reader and Writer: input and output buffering to their respective derivations. As I said before, input

777

buffering entails prefetching data and caching it in memory so that read operations don't have to fetch the data
off a slow device. Output buffering applies write operations to a memory image that's periodically written out to

a stream.

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
BufferedInputStream
and BufferedOutputStream have all of the methods that
By Richard Hightower

InputStream and OutputStream have plus the following:


BufferedInputStream:

Publisher: Addison Wesley


Pub Date: June 28, 2002

ISBN: 0-201-61616-5
Table of
__init__(InputStream)
Pages: 640 creates
Contents

an input buffer for the specified input stream

__init__(InputStream,
as above,
specifies
the size
of the
Characterized by ease iBufSize)
of use, richnessofsame
expression,
andbut
concise
syntax,
Python
hasinput
buffer

remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
BufferedOutputStream:
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.

__init__(OutputStream) creates an output buffer for the specified output stream

This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises
and interactive
sessions,the
this
book
willoutput
__init__(OutputStream,
iBufSize)
same asprogramming
above, but specifies
size
of the
help
those
new
to
programming
develop
an
understanding
of
concepts
and
practical
buffer
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows
the ways
that Python
withmethods
Java APIs
for professional
Themark(),markSupported()
,reset()
,skip()
, andinterfaces
flush()
provide
the buffering
application development.
support.
Python
Programming
with
the Java(TM)
Class
Libraries:example
A Tutorial
for Building
BufferedOutput
can be
chained to an
existing
stream, as
the following
shows.
Import Web
and
Enterprise
Applications
with
Jython
covers
important
topics
such
as:
BufferedOutputStream and FileOutputStream.

>>> from java.io import BufferedOutputStream, FileOutputStream


Fundamental programming concepts, including statements, expressions,
interpreters, andinstance
compilers
Create a BufferedOutputStream
chained to a new FileOutputStream instance.
Python basics, including operators, string formatting, namespaces, classes, errors,
>>> out = BufferedOutputStream(FileOutputStream("bufout.bin"))
and exceptions
Write a sequence of bytes from 0 to 16 (0x0 to 0xF in hexadecimal).
Object-oriented programming concepts

>>> out.write([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16])


File input/output
Write a sequence of bytes from 17 to 31 (0x10 to 0x1F in hexadecimal).
Python's intrinsic functions

>>> out.write([17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31])
Formatting, parsing, and manipulating strings
Write 255 (0xFF hexadecimal) a few times.
Interfacing with the Java APIs and working with Java Streams

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


Using Python and Java Swing to create GUIs
...
out.write(255)
...
Working with SQL and JDBC(TM)
Here's another way of writing out a string:
Python and Java applets

>>> str = "Hello"


addition,
>>> for char Inin
str:the book contains instructions for downloading and installing the Python
language
and the Java Development Kit (JDK). Terminology, definitions, explanations,
...
out.write(ord(char))
and
numerous
code samples make this book a useful learning experience.
>>> out.close()
Whether
arelike
a sophisticated
computer userbufout.bin):
new to programming or a serious
The output for the file
createdyou
looks
this (from C:\dat>debug
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.
-d

0E7F:0100
0E7F:0110
0E7F:0120
0E7F:0130

00
10
FF
48

01
11
FF
65

02
12
FF
6C

03
13
FF
6C

777

04
14
FF
6F

05
15
FF
00

06 07-08
16 17-18
FF FF-FF
00-00 00

09
19
FF
00

0A
1A
FF
00

0B
1B
FF
00

0C
1C
FF
00

0D
1D
FF
00

0E
1E
FF
00

0F
1F
FF
00

................
................
................
.Hello..........

Programming
with
Classline
Libraries:
Tutorial
for Building
The first line has thePython
hexadecimal
numbers 0x0
to the
0xF.Java
The second
lists theAnumbers
0x10
to 0xlF. The third
Web and Enterprise Applications with Jython
line contains the 255 (0xFF) we wrote out, and the fourth line contains the "Hello" string we wrote out.
By Richard Hightower

Using BufferedInputStream

Publisher: Addison Wesley

Date: June 28, 2002


Now it's time for a smallPub
example
of BufferedInputStream. This one demonstrates the mark(),
ISBN: 0-201-61616-5
skip()
,
and
reset()
methods.
Table of

Contents

Pages: 640

Import the classes needed, and create the BufferedInputStream instance, chaining it to a
Characterized
FileInputStream
instance. by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
>>> from java.io
BufferedInputStream,
novicesimport
and professionals
alike. In particular, its closeFileInputStream
relationship to Java(TM) makes
>>> input = BufferedInputStream(FileInputStream("bufout.bin"))
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
Mark the position in the file we want to return to.
This tutorial begins with coverage of some of the basics of Python programming. Using
>>> input.mark(100)
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
Read in first three bytes.
(Remember,
we set the first
three bytesthe
to 0x0,
and 0x21,
2, andbreadth
3 in of
techniques.
For experienced
programmers,
book0x1,
demonstrates
Python's
decimalin the last capabilities
example.) and shows the ways that Python interfaces with Java APIs for professional
application development.

>>> input.read(), input.read(), input.read()


(0, 1, 2, 3) Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
Use the skip() method to skip ahead twenty bytes in the file.

>>> input.skip(20)
Fundamental programming concepts, including statements, expressions,
20L
interpreters, and compilers
Thereset() method setsPython
the filebasics,
back to
the position
marked
withformatting,
the mark()
method, which
happens
including
operators,
string
namespaces,
classes,
errors,to
be at the beginning. A reading
of
the
first
three
bytes
proves
this.
and exceptions

>>> input.reset()Object-oriented programming concepts


>>> input.read(), input.read(), input.read()
(0, 1, 2)
File input/output
Reset the file at the beginning.
Use intrinsic
the zeros()
function to create byte arrays to read in the first three lines.
Python's
functions
(The lines aren't real, like lines of text, but refer to the way the hexdump programthat is, the debug
Formatting,
andthree
manipulating
programdisplays the data.)
Then readparsing,
in the first
lines andstrings
display them.

>>>
>>>
>>>
>>>
>>>
>>>
16

input.reset()Interfacing with the Java


# APIs
reset
to the
beginning
and working
with
Java Streams of the file.
from jarray import zeros # import the zeros function
Using Python
and Java#Swing
to create
line1 = zeros(16,
'b')
buffer
toGUIs
read in first 16 bytes
line2 = zeros(16, 'b')
# buffer to read in next 16 bytes
Working 'b')
with SQL and#JDBC(TM)
line3 = zeros(16,
buffer to read in the third 16
input.read(line1)
# read in line 1
Python and Java applets

In addition, the book contains instructions for downloading and installing the Python

>>> input.read(line2),
input.read(line3)
#read indefinitions,
line 2explanations,
and 3
language and the Java
Development Kit (JDK). Terminology,
(16, 16)
and numerous code samples make this book a useful learning experience.
>>> line1 #display
line1
Whether you
are a sophisticated computer user new to programming or a serious
array([0, 1, application
2, 3, 4,
5, 6,Python
7, Programming
8, 9, 10,with
11,
12, 13,Class
14,
15], will
byte)
developer,
the Java(TM)
Libraries
give you insight into the power of Python and the know-how to put it to work.

>>> line2
#display line2
array([16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31], byte)

777

>>> line3 #display line3

array([-1, -1,
-1,Programming
-1, -1, -1,
-1,Java
-1,Class
-1,Libraries:
-1, -1,
-1, -1,
-1, -1, -1], byte)
Python
with the
A Tutorial
for Building
Web and Enterprise Applications with Jython

Compare the output By


to Richard
the hexdump
we did with the debug program.
Hightower
Now let's read in the "Hello" string. This repeats the FileInputStream exercise, so we won't cover it
Publisher: Addison Wesley
in the same detail as before.
Pub Date: June 28, 2002

ISBN: 0-201-61616-5
Read in
the bytes from the "Hello"
string. (A better way would have been to create a Java array of bytes with
Table of

Pages:
640
jarray
, but I wanted to show this way.)
Contents

>>> binstr=input.read(),input.read(),input.read(),input.read(),input.read()
Characterized by ease of use, richness of expression, and concise syntax, Python has
>>> binstr remained
#display
it
a premier programming
language for more than a decade, and is used by
(72, 101, 108,
108,
111)
novices
and professionals
alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
Convert the byte array
to a sequence
of characters.
application
development.

>>> char_seq This


= []
tutorial begins with coverage of some of the basics of Python programming. Using
>>> for num in
binstr:
plenty
of skill-building exercises and interactive programming sessions, this book will
...
char_seq.append(chr(num))
help those new to programming develop an understanding of concepts and practical
...
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
Convert the sequence
of characters
to a string.
application
development.

>>> char_seq Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
['H', 'e', 'l',
'l', 'o']
and Enterprise
Applications with Jython covers important topics such as:
>>> import string
>>> str = string.joinfields(char_seq,
"")
Fundamental programming concepts,
including statements, expressions,
>>> print str
interpreters, and compilers
Hello
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions

DataInput and DataOutput

Object-oriented programming concepts

DataInput and DataOutput read and write primitive Java types from a stream. Since they're interfaces,
input/output
all of their methods, whichFile
follow,
are abstract and so do nothing until they're instantiated.
Python's intrinsic functions

DataInput:

Formatting, parsing, and manipulating strings

readBoolean()
Interfacing with the Java APIs and working with Java Streams

readByte()
Using Python and Java Swing to create GUIs

readFloat()
Working with SQL and JDBC(TM)

readChar()
Python and Java applets

readDouble()
In addition, the book contains instructions for downloading and installing the Python

readInt()language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.

readShort()
Whether you are a sophisticated computer user new to programming or a serious

readLong()
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

readLine()

777

readUTF()

readUnsignedByte()

Python Programming with the Java Class Libraries: A Tutorial for Building

readUnsignedShort()
Web and Enterprise Applications with Jython
By Richard Hightower

readFully(byte_sequence)
Publisher: Addison Wesley
readFully(byte_sequence,
off, len)
Pub Date: June 28, 2002

skipBytes(n)

Table of
Contents

ISBN: 0-201-61616-5
Pages: 640

DataOutput:

Characterized by ease of use, richness of expression, and concise syntax, Python has
write (b)remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
write(byte_sequence)
application development.

writeBoolean(boolean)
This tutorial begins with coverage of some of the basics of Python programming. Using

writeByte(byte)
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical

writeBytes(string)
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional

writeChar(char)
application development.

writeChars(string)
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

writeDouble(double)

writeFloat(float)
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers

writeInt(int)

Python basics, including operators, string formatting, namespaces, classes, errors,


and exceptions

writeLong(long)

writeShort(short)

Object-oriented programming concepts

writeUTF()

File input/output

DataInputStream and
DataOutput
Stream
Python's
intrinsic functions
Formatting, parsing, and
manipulating
strings
The data stream classes, DataInputStream
and
DataOutputStream
, implement the DataInput
andDataOutput interfaces, respectively, reading and writing Java primitive types to a stream. Here are their
Interfacing with the Java APIs and working with Java Streams
methods.
Using Python and Java Swing to create GUIs

DataInputStream:

Working with SQL and JDBC(TM)

__init__ (InputStream) creates a buffered writer with the specified writer output stream
Python and Java applets

DataOutputStream:

In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
numerous code samples
make
this bookreader
a useful
learning
experience.
__init__ and
(InputStream)
creates
a buffered
with
the specified
reader input stream

Whether you are a sophisticated computer user new to programming or a serious


Using DataInputStream
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into,the
power
the know-how
to put it to work.
To demonstrate DataInputStream
we'll
read of
in Python
the file and
we wrote
with DataOutputStream
in the
last interactive session.

777

Import the classes needed.

>>> from java.io


DataInputStream,
Pythonimport
Programming
with the Java ClassFileInputStream
Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython

Create a DataInputStream
instance that's chained to a new instance of FileInputStream.
By Richard Hightower

>>> data_in = DataInputStream(FileInputStream("data_out.bin"))


Publisher: Addison Wesley

Pub the
Date:
June 28, 2002
Read in a Boolean from
stream.
Table of

ISBN: 0-201-61616-5

>>> Contents
data_in.readBoolean()
Pages: 640
1
Characterized by ease of use, richness of expression, and concise syntax, Python has
Read in a Byte from
the stream.
remained
a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
>>> data_in.readByte()
the two languages, when used in combination, ideal for Web and distributed enterprise
1
application development.
Read in a Char from
thetutorial
stream.begins with coverage of some of the basics of Python programming. Using
This

plenty of skill-building exercises and interactive programming sessions, this book will

>>> data_in.readChar()
help those new to programming develop an understanding of concepts and practical
'\x1'

techniques. For experienced programmers, the book demonstrates Python's breadth of


capabilities
Read in an Int from
the stream.and shows the ways that Python interfaces with Java APIs for professional
application development.

>>> data_in.readInt()
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
1
and Enterprise Applications with Jython covers important topics such as:
Read in a Long and a Short from the stream.
Fundamentaldata_in.readShort()
programming concepts, including statements, expressions,
>>> data_in.readLong(),
interpreters, and compilers
(1L, 1)
Close the stream.

Python basics, including operators, string formatting, namespaces, classes, errors,


and exceptions

>>>data_in.close()
Object-oriented programming concepts
Using DataOutputStream
File input/output
Though not very creative, the
following
example
shows how to write the Java primitive types using
Python's
intrinsic
functions
DataOutputStream:
Formatting, parsing, and manipulating strings

>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>

from java.io import DataOutputStream, FileOutputStream


data_out = DataOutputStream(FileOutputStream("data_out.bin"))
Interfacing with the Java APIs and working with Java Streams
data_out.writeBoolean(1)
Using Python and Java Swing to create GUIs
data_out.writeByte(1)
data_out.writeChar(1)
Working with SQL and JDBC(TM)
data_out.writeInt(1)
data_out.writeLong(1)
Python and Java applets
data_out.writeShort(1)
data_out.close()
In addition, the book contains instructions for downloading and installing the Python

language and the Java Development Kit (JDK). Terminology, definitions, explanations,
Here's a hexdump listing of data_out.bin:
and numerous code samples make this book a useful learning experience.

0E7F:0100 01 01 00 01 00 00 00 01-00 00 00 00 00 00 00 01 ................


Whether you are a sophisticated computer user new to programming or a serious
0E7F:0110 00 01 FF FF FF FF FF FF-FF FF FF FF FF FF FF FF ................
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

readUTF() and writeUTF()

777

Two methods that make life easier are readUTF() and writeUTF(), which read and write strings in
Unicode (UTF-8 transformation format).

Here's an example ofPython


writingProgramming
two strings:

>>>
>>>
>>>
>>>
>>>

with the Java Class Libraries: A Tutorial for Building


Web and Enterprise Applications with Jython
By Richard
Hightower
java.io
import
*

from
out = DataOutputStream(FileOutputStream("strs.bin"))
out.writeUTF("Hello
world")
Publisher: Addison
Wesley
out.writeUTF("
Hello
earth")
Pub Date: June 28, 2002
out.close() ISBN: 0-201-61616-5

Table of

Pages: 640

Here'sContents
an example of reading two strings:

Characterized by ease of use, richness of expression, and concise syntax, Python has

>>> input = DataInputStream(FileInputStream("strs.bin"))


remained a premier programming language for more than a decade, and is used by
>>> input.readUTF()
novices and professionals alike. In particular, its close relationship to Java(TM) makes
'Hello world'
the two languages, when used in combination, ideal for Web and distributed enterprise
>>> input.readUTF()
application development.
' Hello earth'
>>> input.close()
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
As you can see, it is a lot easier to write strings with this technique than with the others we had to use without
help those new to programming develop an understanding of concepts and practical
DataInputStream and DataOutputStream.
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
The File Class
application development.
Python
Programming
with the
Libraries:
A It
Tutorial
The Java File class
is nothing
like the Python
fileJava(TM)
object, inClass
spite of
the name.
allows for
youBuilding
to checkWeb
the
and
Enterprise
Applications
with
Jython
covers
important
topics
such
as:
following attributes of a file:
Read
Write
Size

Fundamental programming concepts, including statements, expressions,


interpreters, and compilers
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions

Object-oriented programming concepts


Last modification date
File input/output
Directory or not a directory
Python's
intrinsic
functions
It also provides the methods
listed below
to view
a directory's contents, to create and delete directories, and to
delete directory files:
Formatting, parsing, and manipulating strings
Interfacing
with the Java
APIs and
working
with Java Streams
canRead() determines
permission
and access
to read
the file
Using Python
and Java
to create
canWrite() determines
read-only
or Swing
read/write
accessGUIs
Working
with SQL
and JDBC(TM)
delete() deletes
the current
file referenced
by this file object
Python
and Java
applets
equals(File)
determines
if the
file referenced by this object is the same as the argument
In determines
addition, the
contains
exists()
if book
the file
exists instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,

getPath()and
gets
the filecode
pathsamples
(can be make
relative)
numerous
this book a useful learning experience.
getAbsolutePath()
same
as above, computer
but resolves
relative
absolute pathsor a serious
Whether you are
a sophisticated
user
new totoprogramming
application developer, Python Programming with the Java(TM) Class Libraries will

getCanonicalPath()
give you insight into the power of Python and the know-how to put it to work.
getName() gets the file name

777

getParent() gets the parent directory

isAbsolute()
Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython

isDirectory()
determines
By Richard
Hightower if the file is a directory
isFile() determines if the file is a regular file
Publisher: Addison Wesley

Pub Date:
June
2002
lastModified()
gets
the28,
date
the file was last modified

ISBN: 0-201-61616-5
Table of
length()
gets Pages:
the length
640of the file
Contents

list() lists
the files in by
theease
directory
Characterized
of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by

list(filter)
and
listsprofessionals
the files in the
directory
with a filter
novices
alike.
In particular,
its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.

mkdir(dir) creates a directory

mkdirs() creates several directories

File

This tutorial begins with coverage of some of the basics of Python programming. Using
plenty
of skill-building
renameTo()
renames
the file exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques.
programmers,
book demonstrates
Python's
of )
toString()
returnsFor
theexperienced
string equivalent
of the filethe
(toString
is inherited
frombreadth
Object
capabilities and shows the ways that Python interfaces with Java APIs for professional
development.
Interactiveapplication
Session

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
Let's look at an example
of File. Import
the File
from
the java.io
package.
and Enterprise
Applications
with class
Jython
covers
important
topics such as:

>>> from java.io import File


Fundamental programming concepts, including statements, expressions,
Create an instance of the file
object thatand
refers
to the properties of the file (c:\\dat\\File.txt).
interpreters,
compilers

>>> file = File("c:\\dat\\File.txt")


Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
Determine if the file is read-only by calling canWrite(). If canWrite() returns 1 (true), the file is
read/write. (If you change the
properties of programming
the file to read-only,
canWrite() returns 0, that is, false.)
Object-oriented
concepts

>>> file.canWrite()
File input/output
1
Python's intrinsic functions
Determine if the file exists. If not, the exists() function returns 0.
Formatting, parsing, and manipulating strings

>>> file.exists()
1
Interfacing with the Java APIs and working with Java Streams
Get just the file name without
thePython
path. and Java Swing to create GUIs
Using

>>> file.getName()
Working with SQL and JDBC(TM)
'File.txt'
Python and Java applets
Get the file path.

In addition, the book contains instructions for downloading and installing the Python

>>> file.getPath()
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
'c:\\dat\\File.txt'
and numerous code samples make this book a useful learning experience.
Get the path of the parent
directory.
Whether
you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
>>> file.getParent()
give you insight into the power of Python and the know-how to put it to work.

'c:\\dat'

777

In the following code, we'll see if the file is a directory. Then we'll create a File instance that refers to the file's
parent directory and test if the directory is actually a directory.

Is the file a directory?


(1 means
yes; 0 meanswith
no) the Java
Python
Programming

>>>
0

Class Libraries: A Tutorial for Building


Web and Enterprise Applications with Jython
file.isDirectory()
By Richard Hightower
Publisher: Addison Wesley

Create a File instance that refers to the file's parent directory, and then see if the directory is a directory.
Pub Date: June 28, 2002

ISBN: 0-201-61616-5
>>> Table
directory
= file(File.getParent())
of

Pages:
640
>>> Contents
directory.isDirectory()
1

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
>>> file.isFile()
the two languages, when used in combination, ideal for Web and distributed enterprise
1
application development.
Is the file a file?

Is the directory a file?


This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
>>> directory.isFile()
help those new to programming develop an understanding of concepts and practical
0
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
ThelastModified() method returns the time, as a Long, which refers to the milli-seconds elapsed since
application development.
Jan. 1, 1970.

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web

>>> file.lastModified()
and Enterprise Applications with Jython covers important topics such as:
934294386000L

You can convert the LongFundamental


to a date using
the following
technique.
Importstatements,
the Date expressions,
class, passing its last
programming
concepts,
including
modified value to its constructor.
interpreters, and compilers

>>>
>>>
>>>
Tue

from java.util
import
Date operators, string formatting, namespaces, classes, errors,
Python
basics, including
date = Date(File.lastModified())
and exceptions
print date
Aug 10 07:13:06
PDT 1999
Object-oriented
programming concepts

Get the length of the file. File input/output

>>> file.length()Python's intrinsic functions


63L
Formatting, parsing, and manipulating strings
Is the class an absolute path (c:\dat\text.tx) or a relative path (..\..\text.txt)?
Interfacing with the Java APIs and working with Java Streams

>>> file.isAbsolute()
1
Using Python and Java Swing to create GUIs
with SQL
andlength.
JDBC(TM)
Delete the file and check toWorking
see if it exists;
get its

>>> file.delete()Python and Java applets


1
In addition, the book contains instructions for downloading and installing the Python
language and the Java #
Development
(JDK). Terminology,
>>> file.exists()
File noKitlonger
exist definitions, explanations,
and
numerous
code
samples
make
this
book
a
useful
learning experience.
0
Whether you are a sophisticated
user new is
to programming
or a serious
>>> file.length()
# Thus computer
its length
zero
application
developer,
Python
Programming
with
the
Java(TM)
Class
Libraries will
0L
give you insight into the power of Python and the know-how to put it to work.
Create a new File instance that refers to the relative location of autoexec.bat.

777

>>> file = File ("..\\..\\..\\autoexec.bat")

Check to see if the file


exists.Programming
Python

>>>
1

with the Java Class Libraries: A Tutorial for Building


Web and Enterprise Applications with Jython
file.exists()
By Richard Hightower
Publisher: Addison Wesley

Get the path (note that it's relative).

Pub Date: June 28, 2002

ISBN: 0-201-61616-5
>>> Table
file.getPath()
of

Pages:
640
'..\\..\\..\\autoexec.bat'
Contents

by ease of use, richness of expression, and concise syntax, Python has


Get the absolute pathCharacterized
(this looks weird).
remained a premier programming language for more than a decade, and is used by
>>> file.getAbsolutePath()
novices and professionals alike. In particular, its close relationship to Java(TM) makes
'C:\\book\\..\\..\\..\\autoexec.bat'
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
Get the canonical path (this looks better).
This tutorial begins with coverage of some of the basics of Python programming. Using
>>> file.getCanonicalPath()
plenty of skill-building exercises and interactive programming sessions, this book will
'C:\\AUTOEXEC.BAT'
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
Path
Separators:
application
development. Sometimes \\, Sometimes/
theoperating
Java(TM)
Classyou're
Libraries:
Tutorial
Building
The path separator Python
can varyProgramming
depending onwith
what
system
using,A so
it's notfor
a good
idea Web
to
and Enterprise
Applications
with Jython
topics
such as:
hardcode it. On Windows
machines,
the path separator
is \,covers
but onimportant
Unix it's /
.
Given this situation, the proper way to create the directory string is
Fundamental programming concepts, including statements, expressions,
interpreters,
and compilers
>>> new_directory
= directory.getCanonicalPath()
+ File.separator \

...
not

+ "MyNewDir"
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions

Object-oriented
programming concepts
>>> new_directory
= directory.getCanonicalPath()
\
+ "\\MyNewDir"
File input/output

File class instances can work


withintrinsic
directories
as well. Create a relative directory that points to the current
Python's
functions
directory.

Formatting, parsing, and manipulating strings

>>> directory = File(".")


>>> directory.isAbsolute()
Interfacing with the Java APIs and working with Java Streams
0
Using Python and Java Swing to create GUIs
List the files in the current directory (an array of Java strings is returned).
Working with SQL and JDBC(TM)

>>> directory.list()
array(['TOC2.txt',
'readme.txt',
Python
and Java applets 'Silver', 'status.xls', 'TOC.txt', 'chap9',
'chap5', 'chap3', 'chap2', 'chap10', 'chap1', '~WRL1019.tmp', '~WRL0244.tmp',
In addition,
the book contains instructions
for downloading'chap6',
and installing 'scripts',
the Python
'~WRL2798.tmp',
'~WRL2319.tmp',
'Code Samples',
'Gold'],
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
java.lang.String)
and numerous code samples make this book a useful learning experience.
Let's create a new directory called MyNewDir. First create the directory string.
Whether you are a sophisticated computer user new to programming or a serious
>>> new_directory
= developer,
directory.getCanonicalPath()
+ "\\MyNewDir"
application
Python Programming with the Java(TM)
Class Libraries will
give you insight into the power of Python and the know-how to put it to work.
Show it.

777

>>> print new_directory


C:\book\MyNewDir

Create an instance ofPython


the directory
that will be
created.
Programming
with
the Java

>>> newDir

Class Libraries: A Tutorial for Building


Web and Enterprise Applications with Jython
= By
File(new_directory)
Richard Hightower

See if the directory to which the instance refers already exists.


Publisher: Addison Wesley

Pub Date: June 28, 2002


>>> newDir.exists()
ISBN: 0-201-61616-5
0
Table of

Pages: 640

Contents

Create the directory with the mkdir() method.


Characterized by ease of use, richness of expression, and concise syntax, Python has
>>> newDir.mkdir()
remained a premier programming language for more than a decade, and is used by
1
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
See if it exists (it should).
application development.

>>> newDir.exists()
This tutorial begins with coverage of some of the basics of Python programming. Using
1
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced
programmers, the book demonstrates Python's breadth of
The RandomAccessFile
Class
capabilities and shows the ways that Python interfaces with Java APIs for professional
application
development.
RandomAccessFile
both reads
and writes to binary output streams. It's most similar to the Python file
object and has the following methods:
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
__init__(strName, strMode) opens the file in the specified mode

Fundamental
programming
including
expressions,
__init__(File,
strMode)
same asconcepts,
above, but
passes astatements,
Java file object
interpreters, and compilers

getFD() gets the file descriptor

Python basics, including operators, string formatting, namespaces, classes, errors,


and exceptions
getFilePointer()
similar to the tell() method for the Python file object
concepts
length() getsObject-oriented
the length of theprogramming
file

seek() similar File


to theinput/output
seek() method for the Python file object
Python's intrinsic
functions
read(byte_sequence)
similar
to the read() method in InputStream
Formatting, parsing,
manipulating
read(byte_sequence,
off, and
len)
similar tostrings
the read() method in InputStream
Interfacing
withDataInput
the Java APIs: and working with Java Streams
The following abstract methods
are from
Using Python and Java Swing to create GUIs

readBoolean()
Working with SQL and JDBC(TM)

readByte()
Python and Java applets

readFloat()
In addition, the book contains instructions for downloading and installing the Python

readChar()
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.

readDouble()
Whether you are a sophisticated computer user new to programming or a serious

readInt()application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

readShort()

777

readLong()
readLine()

readUTF()Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

readUnsignedByte()

Publisher: Addison Wesley


readUnsignedShort()
Pub Date: June 28, 2002

readFully(byte_sequence)
ISBN: 0-201-61616-5

Table of
Pages: 640
Contents
readFully(byte_sequence,

off, len)

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
write (b)novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application
These abstract methods
are fromdevelopment.
DataOutput:

skipBytes(n)

This tutorial begins with coverage of some of the basics of Python programming. Using

write(byte_sequence)
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical

writeBoolean(boolean)
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional

writeByte(byte)
application development.

writeBytes(string)
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
writeChar(char)

writeChars(string)
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
writeDouble(double)
Python basics, including operators, string formatting, namespaces, classes, errors,
writeFloat(float)
and exceptions

writeInt(int)

Object-oriented programming concepts

writeLong(long)

File input/output

writeShort(short)

Python's intrinsic functions

writeUTF(string)

Formatting, parsing, and manipulating strings


Interfacing with the Java APIs and working with Java Streams

Advanced
Note:
The
Shortcoming
of Single
Using Python
and Java
Swing
to create GUIs
Inheritance
Working with SQL and JDBC(TM)
Instead of RandomAccessFile
inheriting from both InputStream and
Python and Java applets
OutputStream, it inherits from DataInput and DataOuput (which are interfaces). Of
course, it could
inherited
fromcontains
these stream
classesfor
if they
were interfaces,
but because
In have
addition,
the book
instructions
downloading
and installing
the Python
RandomAccessFile
them, itKit
can't
chain Terminology,
to them.
language and doesn't
the Javasupport
Development
(JDK).
definitions, explanations,
and numerous code samples make this book a useful learning experience.
A while back I wanted a random access file that worked with ObjectOutputStream and
ObjectInputStream
. Toa sophisticated
get it I had to computer
write my own
extended from
Whether you are
user class
new tothat
programming
or a serious
ObjectOutput
and ObjectInput
and re-implement
streaming.
ThisLibraries
is a situation
application
developer, Python, Programming
withobject
the Java(TM)
Class
will
where the single
of power
Java falls
short. and the know-how to put it to work.
giveinheritance
you insightmodel
into the
of Python

777

RandomAccessFile Modes

TheRandomAccessFile
modes are r for
read
only,
which
is similar
to Python's
r, andfor
rwBuilding
for read/write,
Python Programming
with
the
Java
Class
Libraries:
A Tutorial
which is similar to Python's
r+Enterprise
. Working with
RandomAccessFile
isn't much different from working
Web and
Applications
with Jython
withDataInputStream
DataOutputStream. It's also not much different from working with the
By Richardand
Hightower
Python file object, as I said before. Since there are no truly new concepts here, this next interactive session is a
short one. (You still have
to followAddison
along, though.)
Publisher:
Wesley
Pub Date: June 28, 2002

ImportRandomAccessFile from java.io.

>>>

ISBN: 0-201-61616-5
Table of
Pages:
640 RandomAccessFile
from java.io import
Contents

bymode.
ease of use, richness of expression, and concise syntax, Python has
Create an instance ofCharacterized
it in read/write
remained a premier programming language for more than a decade, and is used by
>>> file = RandomAccessFile("c:\\dat\\rFile.bin",
"rw")
novices and professionals alike. In particular, its close relationship
to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
Create an array that can
be written
to the file; write it to the file.
application
development.

>>> import jarray


This tutorial begins with coverage of some of the basics of Python programming. Using
>>> byte_array
= ofjarray.array((0,1,2,3,4,5,6,7,8,9,10),
plenty
skill-building exercises and interactive programming sessions, 'b')
this book will
>>> print byte_array
help those new to programming develop an understanding of concepts and practical
array([0, 1, techniques.
2, 3, 4,
6, 7,programmers,
8, 9, 10],
byte)
For 5,
experienced
the book
demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional

>>> file.write(byte_array)
application development.
Write some strings toPython
the file.
Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

>>> file.writeUTF("Hello")
>>> file.writeChars(" how are you")
>>> file.writeBytes("
fine
thanks")
Fundamental
programming
concepts, including statements, expressions,

interpreters, and compilers


Get the location in the file.
Python basics, including operators, string formatting, namespaces, classes, errors,
>>> file.getFilePointer()
and exceptions

54L
>>> location = file.getFilePointer()
Object-oriented programming concepts# Save it for later
Move to the start of the fileFile
using
the seek() method.
input/output

>>> file.seek(0) Python's intrinsic functions


Create an empty array ( buffer
), andparsing,
read in the
from byte_array
(written a few steps back).
Formatting,
andvalues
manipulating
strings
Notice that buffer's values are the same as byte_array's values after the file.read() function call.
Interfacing with the Java APIs and working with Java Streams

>>> buffer = jarray.zeros(11, 'b')


Using Python and Java Swing to create GUIs
>>> file.read(buffer)
11
>>> print buffer Working with SQL and JDBC(TM)
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], byte)
Python and Java applets

Move to the saved location; show that it's the same place in the file.
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
>>> file.seek(location)
and numerous code samples make this book a useful learning experience.
>>> file.getFilePointer()

54L

Whether you are a sophisticated computer user new to programming or a serious


application
developer,
Python
Programming with the Java(TM) Class Libraries will
Write the buffer to the
file and show
its current
location.
give you insight into the power of Python and the know-how to put it to work.

>>> buffer[10] = 0xa


>>> file.write(buffer)
>>> file.getFilePointer()
65L

777

Python Programming with the Java Class Libraries: A Tutorial for Building

>>> file.close()
Web and Enterprise Applications with Jython
By Richard Hightower
Publisher: Addison Wesley

Unicode

Pub Date: June 28, 2002

Unicode is a standard for working


with character sets from all common languages. It's essential for internationalizing
ISBN: 0-201-61616-5
Table of
software.

Pages: 640
Contents

Are you the least bit curious about the differences between writeUTF(),writeChars(), and
Characterized by ease of use, richness of expression, and concise syntax, Python has
writeBytes()? Here they are:
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
>>> file.writeUTF("Hello")
the two languages,
whenare
used you")
in combination, ideal for Web and distributed enterprise
>>> file.writeChars("
how
application
development.
>>> file.writeBytes(" fine thanks")

This tutorial begins


withUnicode
coverage
of some of the
of Python
Using
In essence, writeChars()
writes the
representation
of basics
the characters
to programming.
the file; writeUTF()
and
plenty
of
skill-building
exercises
and
interactive
programming
sessions,
this
book
will
writeBytes() write out the ASCII equivalents. (More precisely, writeUTF() writes in a Java-modified
UTF-8
helpread
those
newin
tothe
programming
develop an understanding
of concepts and
practical
format, which you can
about
Java API documentation
under the DataInput
interface.
In the previous
For experienced
interactive example,techniques.
UTF-8 equated
to ASCII.) programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
development.
The Unicode data inapplication
this example
is represented by two bytes, whereas the writeBytes() and writeUTF() data
is represented by one byte. Fire up a hexdump utility, and see for yourself (this is a hexdump of the rfile.bin file):
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
Enterprise Applications with Jython covers important topics such as:
C:\dat>debugandrFile.bin

-d
1876:0100 00 01 02 03 04 05 06 07-08 09 0A 00 05 48 65 6C .............Hel
Fundamental programming concepts, including statements, expressions,
1876:0110 6C 6F 00 20 00 68 00 6F-00 77 00 20 00 61 00 72 lo. .h.o.w. .a.r
interpreters, and compilers
1876:0120 00 65 00 20 00 79 00 6F-00 75 20 66 69 6E 65 20 .e. .y.o.u fine
1876:0130 74 68 Python
61 6E
6B including
73 00 operators,
01-02 03
05 06namespaces,
07 08 09
thanks..........
basics,
string04
formatting,
classes,
errors,
1876:0140 0A 02 and
D3exceptions
74 0A 41 3C 22-75 E6 80 F7 20 EB E1 5E ...t.A<"u... ..^
1876:0150 58 C3 A1 D7 D7 8B 36 D9-D7 C6 06 1B D9 00 C6 06 X.....6.........
1876:0160 17 D9 Object-oriented
00 8B 36 D9
D7 8B-0E
D7 D7 8B D6 E3 42 51 ....6.........BQ
programming
concepts
1876:0170 56 5B 2B DE 59 03 CB 8B-D6 C6 06 BB DB 00 E3 31
V[+.Y..........1File input/output
Notice that the how are
you in
the right
column, which was written with writeChars(), has a period (".")
Python's
intrinsic
functions
between each character, while the Hello and the fine thanks don't. This shows that how are you is using 2Formatting, parsing, and manipulating strings
byte Unicode.

Interfacing with the Java APIs and working with Java Streams

The StreamTokenizer
Class
Using Python and Java Swing to create GUIs
StreamTokenizer breaks
up an
input
stream
into tokens and can be used to parse a simple file (excuse
Working
with
SQL
and JDBC(TM)
me, "input stream"). Read the Java API documentation on StreamTokenizer, and then compare what you
Python and Java applets
read to the following methods
In addition, the book contains instructions for downloading and installing the Python

__init__(Reader)
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.

__init__(InputStream)

Whether you are a sophisticated computer user new to programming or a serious

nextToken()
returns
the nextPython
token inProgramming
the stream with the Java(TM) Class Libraries will
application
developer,
give you insight into the power of Python and the know-how to put it to work.

lineno() returns the current line number

777

lowerCaseMode(flag) returns all words to lowercase if passed a true value


parseNumbers() sets the parsing of floating-point numbers

Python
Programming
withonto
thethe
Java
Class
Libraries:
A Tutorial
for Building
pushBack()
pushes
the token back
stream,
returning
it to the
next nextToken()

method call

Web and Enterprise Applications with Jython


By Richard Hightower

quoteChar(char) specifies the character string delimiter; the whole string is returned as a token
Publisher: Addison Wesley
insval
Pub Date: June 28, 2002

resetSyntax()ISBN:
sets0-201-61616-5
all characters to ordinary so that they aren't ignored as tokens

Table of
Pages: 640
Contents
commentChar(char) specifies

a character that begins a comment that lasts until the end of the
line; charactersCharacterized
in a commentbyare
not
returned
ease of use, richness of expression, and concise syntax, Python has

remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
comment)
the two languages, when used in combination, ideal for Web and distributed enterprise
application development. allows recognition of /* */ to denote a comment
slashStarComments(flag)

slashSlashComments(flag) allows recognition of // to denote a comment (this is a Java

This tutorial begins with coverage of some of the basics of Python programming. Using
toString()
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming
develop
an understanding
concepts
practical
whitespaceChars(low,hi)
specifies
the range
of charactersofthat
denote and
delimiters
techniques. For experienced programmers, the book demonstrates Python's breadth of
wordChars(low,
specifies
the range
of characters
thatwith
makeJava
up words
capabilitieshi)
and
shows
the ways
that Python
interfaces
APIs for professional
application development.
ordinaryChar(char) specifies a character that is never part of a token (the character should be
returned as is)Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
ordinaryChars(low, hi) specifies a range of characters that are never part of a token (the
character should be returned as is)
Fundamental programming concepts, including statements, expressions,
eolSignificant(flag)
if end-of-line (EOL) characters are significant (they're
interpreters,
andspecifies
compilers
ignored if not, i.e., treated like whitespace)
Python basics, including operators, string formatting, namespaces, classes, errors,
StreamTokenizer's variables
are ttype (one of the constant values TT_EOF,TT_EOL,
and exceptions
TT_NUMBER, and TT_WORD) ;sval (contains the token of the last string read); and nval (contains the
Object-oriented programming concepts
token of the last number read).
File input/output

Using StreamTokenizer

Python's intrinsic functions


Reading the documentation probably isn't enough to get you started with StreamTokenizer, so we're
Formatting,
and manipulating
going to work with a simple
applicationparsing,
that produces
a report on strings
the number of classes and functions in a
Python source file. Here's the source code:
Interfacing with the Java APIs and working with Java Streams

class MyClass:
#This is my class
Using Python and Java Swing to create GUIs
def method1(self):
pass
Working with SQL and JDBC(TM)
def method2(self):
passPython and Java applets
#Comment should
be ignored
In addition,
the book contains instructions for downloading and installing the Python
def AFunction():
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
pass and numerous code samples make this book a useful learning experience.
class SecondClass:
Whether you are a sophisticated computer user new to programming or a serious
def m1(self):
application developer, Python Programming with the Java(TM) Class Libraries will
print
"Hi into
Mom"
#Sayand
hitheto
mom to put it to work.
give
you insight
the power of Python
know-how
def m2(self):
print "Hi Son"
#Say hi to Son

777

#Comment should be ignored

def BFunction():
Python Programming with the Java Class Libraries: A Tutorial for Building
pass Web and Enterprise Applications with Jython
By Richard Hightower

Follow along with the next interactive session. Afterward we'll look at the code to count the classes and
functions.
Publisher: Addison Wesley
Pub Date: June 28, 2002
Import the FileInputStream
class from java.io, and create an instance of it.

>>>

ISBN: 0-201-61616-5
Table of
Pages:
640 FileInputStream
from java.io import
Contents

>>> file = FileInputStream("C:\\dat\\ParseMe.py")


Characterized by ease of use, richness of expression, and concise syntax, Python has
Import the StreamTokenizer
class,
and create anlanguage
instancefor
of more
it. Pass
its constructor
theis used by
remained a premier
programming
than
a decade, and
FileInputStream
instance.
novices
and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
>>> from java.io
import
StreamTokenizer
application
development.

>>> token = StreamTokenizer(File)


This tutorial begins with coverage of some of the basics of Python programming. Using
CallnextToken()
to get
first token exercises
in the file and
(thatinteractive
is, class). programming sessions, this book will
plenty
of the
skill-building
help those new to programming develop an understanding of concepts and practical
>>> token.nextToken()
techniques. For experienced programmers, the book demonstrates Python's breadth of
-3
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
As you can see, nextToken() returns a numeric value, although you may have been expecting a string value
containing"class"
. In fact,
nextToken()
the type
ofLibraries:
token, thatAis,Tutorial
a word,for
a number,
an EOL
Python
Programming
with thereturns
Java(TM)
Class
BuildingorWeb
or EOF (end-of-file)and
character,
so
-3
refers
to
TT-WORD
.
Enterprise Applications with Jython covers important topics such as:
Thettype variable holds the last type of token read.
Fundamental programming concepts, including statements, expressions,
>>> token.ttype interpreters, and compilers

-3

Python basics, including operators, string formatting, namespaces, classes, errors,


Thesval variable holds the
last token read. If we want to check if the last token type was a word, we
andactual
exceptions
can write this, and, if it was a word, we can print it out.
Object-oriented programming concepts

>>> if token.ttype == token.TT_WORD:


...
print token.sval
File input/output
...
class
Python's intrinsic functions
>>>

Formatting, parsing, and manipulating strings


CallnextToken() again to get the next token, which is MyClass.
Interfacing with the Java APIs and working with Java Streams

>>> token.nextToken()
Using Python and Java Swing to create GUIs
-3
Working with SQL and JDBC(TM)
>>> print token.sval
MyClass
Python and Java applets

CallnextToken() again; this time it should return the '#' token.


In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
>>> token.nextToken()
and numerous code samples make this book a useful learning experience.
58

Whether you are a sophisticated computer user new to programming or a serious

>>> print token.sval


application developer, Python Programming with the Java(TM) Class Libraries will
None
give you insight into the power of Python and the know-how to put it to work.

Since the token is a ':'StreamTokenizer doesn't recognize it as valid. The only valid types are
NUMBER,EOL,EOF, and WORD. So for ':' to be recognized, it has to be registered with the
wordChars() method.

777

>>> token.TT_NUMBER
Python Programming with the Java Class Libraries: A Tutorial for Building
-2
Web and Enterprise Applications with Jython
By Richard Hightower

>>> token.TT_EOL
10
Publisher: Addison Wesley
Pub Date: June 28, 2002

>>> token.TT_EOF ISBN: 0-201-61616-5


-1 Table of
Pages: 640
Contents

>>> token.TT_WORD
Characterized by ease of use, richness of expression, and concise syntax, Python has
-3
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
If the type isn't one of these, the number corresponding to the character encoding is returned. Let's see what
the two languages, when used in combination, ideal for Web and distributed enterprise
nextToken() returns for the next character.
application development.

>>> token.nextToken()
This tutorial begins with coverage of some of the basics of Python programming. Using
35
plenty of skill-building exercises and interactive programming sessions, this book will
thoseyou
new
programming
develop ord()
an understanding
The35 refers to '#'help
, which
cantoprove
with the built-in
function. of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
>>> ord('#') capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
35

Get the next token. Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

>>> token.nextToken()
-3

Fundamental programming concepts, including statements, expressions,


interpreters,
and compilers
The token is a word (-3 equates
to TT_WORD
). Print sval to find out what the word is.
Python basics, including operators, string formatting, namespaces, classes, errors,
>>> print token.sval
and exceptions
This
Object-oriented programming
concepts
As you can see, the StreamTokenizer
instance is reading
text out of the comment from the first line. We
want to ignore comments, so we need to return the tokens we took out back into the stream.
File input/output
Push the token back into the stream.
Python's intrinsic functions

>>> token.pushBack()

Formatting, parsing, and manipulating strings


Attempt to push the token before the last one back into the stream.
Interfacing with the Java APIs and working with Java Streams

>>> token.pushBack()

Using Python and Java Swing to create GUIs


SetcommentChar() to ignore '#'. (commentChar() takes an integer argument corresponding to the
encoding of the character.)Working with SQL and JDBC(TM)
Python and Java applets
>>> token.commentChar(ord('#'))
In addition,
the book contains instructions for downloading and installing the Python
Get the next token, and
print it out.
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
>>> token.nextToken()

-3

Whether you are a sophisticated computer user new to programming or a serious


application developer, Python Programming with the Java(TM) Class Libraries will
>>> print token.sval
give you insight into the power of Python and the know-how to put it to work.
This
Are you wondering why we still have the comment text? The pushback() method can only push back the
last token, so calling it more than once won't do any good. Let's start from the beginning, creating a new
FileInputStream instance and a new StreamTokenizer instance.

777

Python Programming
the Java
Class Libraries:
A Tutorial
Create the StreamTokenizer
instance with
by passing
its constructor
a new instance
of for Building
Web and Enterprise Applications with Jython
FileInputStream.
By Richard Hightower

>>> file = fileInputStream("c:\\dat\\parseMe.py")


Publisher: Addison Wesley
>>> token = StreamTokenizer(File)
Pub Date: June 28, 2002

Iterate through the source code,


printing
out the words in the file. Quit the while loop when the token type is
ISBN:
0-201-61616-5
EOF. Table of
Pages: 640
Contents

>>> while token.ttype


Characterized by!=
easetoken.TT_EOF:
of use, richness of expression, and concise syntax, Python has
...
token.nextToken()
remained a premier programming language for more than a decade, and is used by
...
if(token.ttype
== token.TT_WORD):
novices and professionals
alike. In particular, its close relationship to Java(TM) makes
...
print
token.sval
the two
languages,
when used in combination, ideal for Web and distributed enterprise
application development.
Notice that the comment text isn't in the words printed out.

class
MyClass
def
method1
self
pass
def
method2
self
pass
def
AFunction
pass
...
...

This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
Object-oriented programming concepts

Parsing Python with StreamTokenizer

File input/output
Okay, we've done our experimentation. Now it's time for the actual code for counting the classes and functions
in our Python source code. Python's intrinsic functions
Formatting,
parsing, and manipulating
strings
from java.io import
FileInputStream,
StreamTokenizer
with the
Java APIs andby
working
with Java
# CreateInterfacing
a stream
tokenizer
passing
a Streams
new
# instance of the FileInputStream
Using Python and Java Swing to create GUIs
token = StreamTokenizer(FileInputStream("c:\\dat\\parseMe.py"))
Working with SQL and JDBC(TM)

# Set the comment character.


token.commentChar(ord('#'))
Python and Java applets

In addition, the book contains instructions for downloading and installing the Python
classList = []
functionList language
= [] and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.

# Add an element to a list


Whether you are atoken):
sophisticated computer user new to programming or a serious
def addToList(theList,
application developer, Python Programming with the Java(TM) Class Libraries will
token.nextToken()
give you insight
into the power of Python and the know-how to put it to work.
if (token.ttype
== token.TT_WORD):
theList.append (token.sval)

777

# Adds a class to the class list


def parseClass(token):

global classList
Python Programming with the Java Class Libraries: A Tutorial for Building
addToList (classList,
token)
Web and Enterprise
Applications with Jython
By Richard Hightower

# Adds a function to the function list


def parseFunction(token):
Publisher: Addison Wesley
global functionList
Pub Date: June 28, 2002
addToList (functionList,
token)
ISBN: 0-201-61616-5

Table of
Contents#

Pages: 640

Iterate through the list until the


# token
is ofby ease
type
TT_EOF,
end
of File
Characterized
of use,
richness of
expression,
and concise syntax, Python has
while token.ttype
!=
token.TT_EOF:
remained a premier programming language for more than a decade, and is used by
token.nextToken()
novices and professionals alike. In particular, its close relationship to Java(TM) makes
if(token.ttype
token.TT_WORD):
the two ==
languages,
when used in combination, ideal for Web and distributed enterprise
if (token.sval
== "class"):
application development.
parseClass(token)
elif(token.sval
== coverage
"def"):
This tutorial begins with
of some of the basics of Python programming. Using
parseFunction(token)
plenty
of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical

# Print
outFordetail
about
a function
or classPython's
list breadth of
techniques.
experienced
programmers,
the book demonstrates
def printList(theList,
type):
capabilities and shows
the ways that Python interfaces with Java APIs for professional
print "There
are "development.
+ `len(theList)` + " " + type
application
print theList
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise
Applications with Jython covers important topics such as:
# Print
the results.
printList (classList, "classes")
printList (functionList, "functions and methods")
Here's the output:

There are 2
['MyClass',
There are 6
['method1',

Fundamental programming concepts, including statements, expressions,


interpreters, and compilers

Python basics, including operators, string formatting, namespaces, classes, errors,


classes
and exceptions
'SecondClass']
functions and methods
Object-oriented
programming concepts
'method2',
'AFunction',
'm1', 'm2', 'BFunction']

File input/output
The main part of the code (where all the action is happening) is
Python's
intrinsic functions
# Iterate
through
the list until the
# tokenFormatting,
is of parsing,
type and
TT_EOF,
end of File
manipulating strings
while token.ttype != token.TT_EOF:
token.nextToken()
Interfacing with the Java APIs and working with Java Streams
if(token.ttype == token.TT_WORD):
if (token.sval
== Java
"class"):
Using Python and
Swing to create GUIs
parseClass(token)
Working with SQL
JDBC(TM)
elif(token.sval
== and
"def"):
parseFunction(token)
Python and Java applets
Let's look at it step by step.
In addition, the book contains instructions for downloading and installing the Python
Java
If the token type isn'tlanguage
equal to and
EOFthe
, get
theDevelopment
next token. Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.

while token.ttype != token.TT_EOF:


Whether you are a sophisticated computer user new to programming or a serious
token.nextToken()
application developer, Python Programming with the Java(TM) Class Libraries will
If the token type is WORD
, insight into the power of Python and the know-how to put it to work.
give you

if(token.ttype == token.TT_WORD):

777

check to see if the token is a class modifier. If it is, call the parseClass() function, which uses the

StreamTokenizer
instance
to extract the
class
andClass
put itLibraries:
on a list. A Tutorial for Building
Python
Programming
with
thename
Java
Web and Enterprise Applications with Jython

if (token.sval
== "class"):
By Richard
Hightower
parseClass(token)
Publisher: Addison Wesley

If the token isn't a class modifier, check to see if it's a function modifier. If so, call parseFunction(),
Pub Date: June 28, 2002
which uses StreamTokenizer
to extract the function name and put it on a list.
Table of

elif(token.sval
Contents

ISBN: 0-201-61616-5

Pages:
640
==
"def"):

parseFunction(token)
Characterized by ease of use, richness of expression, and concise syntax, Python has

StreamTokenizer
is a good
way toprogramming
parse an input
stream.for
If you
understand
its runtime
remained
a premier
language
more
than a decade,
and isbehavior
used by (which
andinteractive
professionals
alike.you'll
In particular,
close
to Java(TM) makes
you should from the novices
preceding
session),
be more its
likely
to relationship
use it.
the two languages, when used in combination, ideal for Web and distributed enterprise
The more astute among
you probably
noticed that functions and methods were counted together in the last
application
development.
example. As an exercise, change the code so that each class has an associated list of methods and so that these
tutorial begins with coverage of some of the basics of Python programming. Using
methods are countedThis
separately.
plenty of skill-building exercises and interactive programming sessions, this book will
Hint: You'll need to help
use the
resetSyntax()
method
of StreamTokenizer
to setand
all characters
those
new to programming
develop
an understanding of concepts
practical to
ordinary. Then you'lltechniques.
need to count
spaces (ord(")
) and tabs
(ord("\t")
) that
occur before
Forthe
experienced
programmers,
the book
demonstrates
Python's
breadththeoffirst
word on a line. For this
you alsoand
needshows
to track
you
hit aninterfaces
EOL token
type.
(IfAPIs
you can
this exercise, I
capabilities
thewhether
ways that
Python
with
Java
for do
professional
do believe that you can
do
any
exercise
in
the
book.)
application development.
As another exercise,Python
create aProgramming
stream that can
parse
file whose
contents
look like
this: for Building Web
with
the aJava(TM)
Class
Libraries:
A Tutorial
and Enterprise Applications with Jython covers important topics such as:

[SectionType:SectionName]
value1=1
value2 = 3
#This isprogramming
a comment
thatincluding
should
be ignored
Fundamental
concepts,
statements,
expressions,
value4 = "Hello" interpreters, and compilers

SectionType defines Python


a class of
section
, andoperators,
SectionName
is like defining
a classclasses,
instance.
value
basics,
including
string formatting,
namespaces,
errors,
equates to a class attribute.and exceptions
Here's an example.

Object-oriented programming concepts

[Communication:Host]
File input/output
type = "TCP/IP" #Possible values are TCP/IP or RS-232
Python's
intrinsicthe
functions
port = 978
#Sets
port of the TCP/IP
Formatting, parsing, and manipulating strings
[Communication:Client]
type = "RS-232"
Interfacing with the Java APIs and working with Java Streams
baudrate = 9600
baudrate = 2800 Using Python and Java Swing to create GUIs
baudrate = 19200
Working with SQL and JDBC(TM)

[Greeting:Client]
and Java
applets
sayHello = "Good Python
morning
Mr.
Bond"
In addition, the book contains instructions for downloading and installing the Python
[Greeting:Host]
language
and the Javasir"
Development Kit (JDK). Terminology, definitions, explanations,
sayHello = "Good
morning
and numerous code samples make this book a useful learning experience.
Create a dictionary of dictionaries of dictionaries. The name of the top-level dictionary should correspond to the
Whether you are
a sophisticated
userbe
new
to programming
or a serious
section type (Communication
,Greeting
); its computer
value should
a dictionary
whose name
corresponds to
application
developer,
Python
Programming
with
the Java(TM)
ClassThe
Libraries
the section names (Client
,Host
) and whose
values
correspond
to another
dictionary.
names will
and values
give
you
insight
into
the
power
of
Python
and
the
know-how
to
put
it
to
work.
of the third-level dictionaries should correspond to the name values in the file (sayHello ="Good
morning Mr. Bond", type = "RS-232"). If, like baudrate , the name repeats itself, you
should create a list corresponding to the name baudrate and, instead of a single value inserted in the bottomtier dictionaries, put the list as the value.

777

The structure will look


like this:
Python
Programming

with the Java Class Libraries: A Tutorial for Building


Web and Enterprise Applications with Jython
{}Communication{}
Client {} type = "rs-232"
By Richard Hightower

|
|
|
|
|
- baudrate = [9600, 2800, 19200]
Publisher: Addison Wesley
|
|
Pub Date: June 28, 2002
|
| Host {} type = "TCP/IP"
ISBN: 0-201-61616-5
| Table of
|
Pages: 640
| Contents
- port = 978
|
Characterized by ease of use, richness of expression, and concise syntax, Python has
Greeting -----{} - Client{} - sayHello = "Good morning Mr. Bond"
remained a premier programming language for more than a decade, and is used by
|
novices and professionals alike. In particular, its close relationship to Java(TM) makes
| Host sayHello = "Good morning sir"
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.

Persisting Objects with Java Streams

This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building
exercises
and interactive
sessions,It this
book will for
ObjectOutputStream
writes out Java
class instances
(objects)programming
to an output stream.
accomplishes
help
those
new
to
programming
develop
an
understanding
of
concepts
and
practical
Java what the pickle module does for Python. Only Java instances that have the Serializable class
For experienced
programmers,
the book demonstrates Python's
breadth
of
(interface) as a base techniques.
class (interface)
can be serialized
with ObjectOutputStream
. All Jython
objects
capabilities
and
shows
the
ways
that
Python
interfaces
with
Java
APIs
for
professional
(class instances, functions, dictionaries, lists) implement Serializable.
application development.
Here's a short example. Import ObjectOutputStream and FileOutputStream from the java.io
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
package.
and Enterprise Applications with Jython covers important topics such as:

>>> from java.io import ObjectOutputStream, FileOutputStream


Fundamental programming
concepts,
including statements,
expressions,
Create an instance of ObjectOutputStream
, passing
the constructor
a new instance
of
FileOutputStream.interpreters, and compilers
Python basics, including operators, string formatting, namespaces, classes, errors,
>>> oos = ObjectOutputStream(FileOutputStream("c:\\dat\\out.bin"))
and exceptions

Define a simple class.

Object-oriented programming concepts

>>> class MyClass:


File input/output
...
def __init__(self):
...
self.a
= "a"
Python's intrinsic functions
...
Formatting, parsing, and manipulating strings
Create an instance of the class.
Interfacing with the Java APIs and working with Java Streams

>>> object = MyClass()

Using Python and Java Swing to create GUIs


Write the instance to the output stream with the writeObject() method.
Working with SQL and JDBC(TM)

>>> oos.writeObject(object)
>>> oos.close() Python#From
and Javahere
applets

Now we can use ObjectInputStream


to read
the objectfor
back.
Import ObjectInputStream
In addition, the book contains
instructions
downloading
and installing the Python and
FileInputStream
from
package
java.io.
language and the Java Development Kit (JDK). Terminology, definitions, explanations,

and numerous code samples make this book a useful learning experience.

>>> from java.io import ObjectInputStream, FileInputStream


Whether you are a sophisticated computer user new to programming or a serious
Create an instance of ObjectInputStream.
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.
>>> ois = ObjectInputStream(FileInputStream("c:\\dat\\out.bin"))

777

Read the object from the stream.

>>> object2 = ois.readObject()

Python
Programming
with as
the
Class
Libraries:
A Tutorial
for Building
Show that the attribute
of object2
is the same
theJava
attribute
of object
but
that object
and object2
Web and Enterprise Applications with Jython
aren't the same.
By Richard Hightower

>>> print "The a attribute of object 2 is " + object2.a


>>> print "Are Publisher:
objectAddison
and Wesley
object2 the same? " + `(object is object2)`
Pub Date: June 28, 2002

As I said, object streams function


lot like the pickle module.
ISBN: a0-201-61616-5

Table of

Pages: 640

As an Contents
exercise, modify the address book application from Chapter 8 to use object streams instead of pickle.

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier
programming
language
for more than a decade, and is used by
Using Java Streams
to Work
with
Memory
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the streams
two languages,
when used
in combination,
ideal
forprecisely,
Web andany
distributed
enterprise
We spoke earlier about
being abstract
metaphors
for files or,
more
type of input/output
application
development.
mechanism. With streams, for example, you can write data to a byte array, which is essentially a location in the
computer's memory. ByteArrayInputStream and ByteArrayOutputStream allow reading and
This tutorial begins with coverage of some of the basics of Python programming. Using
writing to and from memory. You might want to look them up in the Java API documentation.
plenty of skill-building exercises and interactive programming sessions, this book will
those new
programming
understanding
concepts
andthe
practical
Instead of passing a help
file stream
to a to
stream
derivation,develop
you cananpass
a byte arrayofstream.
Here's
earlier
techniques.
For
experienced
programmers,
the
book
demonstrates
Python's
breadth of
example showing this (the differences are in bold).
capabilities and shows the ways that Python interfaces with Java APIs for professional
from java.io application
import development.
ObjectOutputStream, ByteArrayOutputStream

bytes = ByteArrayOutputStream()
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
oos = ObjectOutputStream(bytes)
and Enterprise Applications with Jython covers important topics such as:

class MyClass:
def __init__(self):
Fundamental programming concepts, including statements, expressions,
self.a interpreters,
= "a" and compilers
object = MyClass()
Python basics, including operators, string formatting, namespaces, classes, errors,
oos.writeObject(object)
and exceptions
oos.close()
print "Here is the
binary image
on concepts
a Jython class instance"
Object-oriented
programming
print bytes.toByteArray()
File input/output

from java.io import ObjectInputStream, ByteArrayInputStream


Python's intrinsic functions
ois = ObjectInputStream(ByteArrayInputStream(bytes.toByteArray()))
object2 = ois.readObject()
Formatting, parsing, and manipulating strings

print "The a attribute


2 is
" + object2.a
Interfacing of
with object
the Java APIs
and working
with Java Streams
print "Are object and object2 the same? " + `(object is object2)`
Using Python and Java Swing to create GUIs
Note that, to create the ByteArrayInputStream instance, I passed the byte array returned by the
toByteArray() method
of the with
ByteArrayOutputStream
instance. In a later chapter, I'll show you
Working
SQL and JDBC(TM)
how to work with network streams.
Python and Java applets
As an exercise, read the Java API documentation on CharArrayReader and CharArrayWriter, and
In addition,
book
contains
instructions
downloading
and installing the Python
write a simple program
that readsthe
and
writes
text strings
to andfor
from
a memory location.
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.

Summary

Whether you are a sophisticated computer user new to programming or a serious


Streams are Java's way
to support
I/O. TheyPython
can represent
a file, awith
network
connection,
or access
to awill
Web site.
application
developer,
Programming
the Java(TM)
Class
Libraries
In this chapter, we dealt
with file
because
they're
work withtoand
givemostly
you insight
intostreams
the power
of Python
andeasy
the to
know-how
putdemonstrate
it to work. stream
fundamentals. Learning to deal with Java streams is essential for learning to use the Java APIs.

777

We covered some nonstream classesRandomAccessFile,File, and StreamTokenizer. As we


saw in the examples, RandomAccessFile works most like the Python file object. The Java File class

allows access to a file's


attributes:
Is the file read-only?
Is it a directory?
and so forth.
It alsofor
allows
the creation
Python
Programming
with the Java
Class Libraries:
A Tutorial
Building
of directories. The StreamTokenizer
class works with
text stream (a class derived from Reader) or
Web and Enterprise Applications
withany
Jython
binary stream (a classByderived
InputStream).
Richardfrom
Hightower
Streams work with more
than just files. We demonstrated the ByteArrayInputStream and the
Publisher: Addison Wesley
ByteArrayOutputStream classes, which allow reading and writing to memory buffers.
Pub Date: June 28, 2002

Table of
Contents

ISBN: 0-201-61616-5
Pages: 640

CONTENTS

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
Object-oriented programming concepts
File input/output
Python's intrinsic functions
Formatting, parsing, and manipulating strings
Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs
Working with SQL and JDBC(TM)
Python and Java applets
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
CONTENTS
Web and Enterprise Applications with Jython
By Richard Hightower

Chapter 13. JFC


Fundamentals
Publisher: Addison Wesley
Pub Date: June 28, 2002

Components and Containers


ISBN: 0-201-61616-5
Table of
JFrame
Pages: 640
Contents
Handling Events with JFrame
by easeEvents
of use, richness of expression, and concise syntax, Python has
The PythonCharacterized
Way of Handling
remained a premier programming language for more than a decade, and is used by
The Class Hierarchy for JFrame and Frame
novices and professionals alike. In particular, its close relationship to Java(TM) makes
JPanel
the two languages, when used in combination, ideal for Web and distributed enterprise
JLabel
application development.
JComponent
JButton This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
JTextField
help those new to programming develop an understanding of concepts and practical
JCheckBoxtechniques. For experienced programmers, the book demonstrates Python's breadth of
JRadioButton
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
List and JList
Summary

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
Terms in This Chapter

Fundamental
programming concepts,Menu
including
statements, expressions,
Abstract
Window Toolkit
(m enubar/popup)
interpreters, and compilers
Checkbox
Mnemonics
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
Container
Model View Controller
Object-oriented programming concepts
Data model
Packing
File input/output
Dropdown
list

Panel

Event Python's
object intrinsic functions

Polymorphism

Formatting, parsing, and manipulating


strings
File path
Radio/Toggle
button
with Java Streams
FrameInterfacing with the Java APIs and working
Single inheritance
Using Python and Java Swing to create
GUIs
gif/jpeg
Superclass
Working with SQL and JDBC(TM) Titlebar
Java APIs
Python and Classes/Swing
Java applets
Java Foundation

Toolbar

In
addition,
the book contains instructions for
downloading and installing the Python
Layout
management
Vector
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
Listener
and
numerous code samples make this book a useful learning experience.
In this chapter, we'reWhether
going toyou
cover
construction computer
of Java GUI
including or
listboxes,
text fields,
arethe
a sophisticated
userapplications,
new to programming
a serious
menus, buttons, windows,
checkboxes,
andPython
panels.Programming
In previous chapters,
played with
applications
application
developer,
with thewe
Java(TM)
ClassJava
Libraries
will to
work with events andgive
Java
classes.
will
be the
here.
you
insightEvents
into the
power
offocus
Python
and the know-how to put it to work.
There are two ways to build GUIs in JavaAbstract Window Toolkit (AWT) and Java Foundation Classes
(JFC)/Swing, which are conceptually similar although very different in execution. JFC is the newer of the two
and is supported only by current browsers. AWT is supported by newer and older browsers, but our AWT tour

777

will include only its Python


post-Swing
incarnation. with the Java
Programming

Class Libraries: A Tutorial for Building


Web and Enterprise Applications with Jython
By Richard Hightower

AWT or JFC

Publisher: Addison Wesley


Pub Date: June 28, 2002

If you can't control the


clientthat
is, what browser he's usingyou may want to use AWT. You'll
ISBN:
0-201-61616-5
Table
of also use it when you're working with hand-held devices. Even so, JFC has many features
probably

Pages: 640
Contents
that have no AWT equivalent, so it's a better general-purpose tool.
Characterized by ease of use, richness of expression, and concise syntax, Python has
Actually, JFCremained
encompasses
both AWT
and Swing,
but Swing
is thethan
newer,
so-called
a premier
programming
language
for more
a decade,
andlightweight
is used by
version of GUI
widgets
(components).
Basically,
Swing
widgets
have
no
operating
system makes
novices and professionals alike. In particular, its close relationship to Java(TM)
counterpart. the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
Learning GUI programming in Java is a fairly tall order, especially when you factor in all of the advanced JFC
with
coverage
of some
of the
basicschapters,
of Python
programming.
controls such as treesThis
andtutorial
tables. begins
Covering
this
topic fully
will take
several
and
even then weUsing
can only
plenty
of more,
skill-building
interactive
sessions, thisisbook
will Java,
cover the basics. If you
want
there areexercises
plenty ofand
good
books outprogramming
there. One I recommend
Graphic
help 1998
those and
new1999),
to programming
develop
an understanding
concepts
practical
volumes 1 and 2 (Geary,
which provides
exhaustive
referencesofand
scores and
of code
examples.
techniques.
For
experienced
programmers,
the
book
demonstrates
Python's
breadth
of
Geary documents components by their properties, which makes them easy for Jython users to read and work
capabilities
and
shows
the
ways
that
Python
interfaces
with
Java
APIs
for
professional
with. Other good sources are the Java tutorial on JFC and the abundant, and free, Java API documentation.
application development.
Like most of the chapters in this book, this one is hands on. For example, we don't go into detail about the
Python
Programming
Java(TM)
Libraries:
A Tutorial
Webto
Model View Controller
(MVC)
architecturewith
thatthe
JFC
uses, butClass
we show
examples
that usefor
it. Building
If you want
and behavior
Enterprise
withtoJython
topics
understand the dynamic
ofApplications
MVC, you have
followcovers
along.important
Repeat after
me:such
Theas:
only way to learn
program ming is to program.

Fundamental programming concepts, including statements, expressions,

Components and
Containers
interpreters,
and compilers

Python basics,
including
operators,
string
namespaces,
classes,
errors,
In Java, you organize components
as nested
elements.
Typically
you formatting,
have a frame,
which contains
several
panels
and
exceptions
and maybe a toolbar and a menubar. In fact, each panel can contain other components such as text fields and
labels or even other panels, so a complete graphical user interface can consist of many nested elements. The JFC
Object-oriented programming concepts
and AWT containers are components themselves and can be contained in other containers. You can see this in
their class diagrams, whichFile
alsoinput/output
show their points of similarity.
Python's intrinsic functions

Design
Patterns
Formatting, parsing,
and manipulating
strings
Interfacing
with thePublish
Java APIs
working
with Java Streams Decorator,
AWT and JFC use the
design patterns
and and
Subscribe,
Observer/Observable,
and Strategy, among others. These are described in Design Patterns (Gamma et al., 1995)a must
Using Python
andJava
JavaAPIs.
Swing to create GUIs
read for a deep understanding
of the
Working with SQL and JDBC(TM)

JFrame

Python and Java applets

addition,that
the pop
bookupcontains
instructions
and installing
the Python
Frames are top-levelIn
interfaces
as windows
and canfor
be downloading
resized and closed.
As containers,
they
language
and components,
the Java Development
definitions,
explanations,
typically contain panels
and other
for whichKit
they(JDK).
initiateTerminology,
layout management.
They
can also have an
numerous code samples make this book a useful learning experience.
associated menubar and icons.
Here's an example ofWhether
how a simple
works usingcomputer
JFrame
. new to programming or a serious
you areframe
a sophisticated
user
application developer, Python Programming with the Java(TM) Class Libraries will
ImportJFrame from
javax.swing.
anpower
instance
of it, show
it, change
give
you insightCreate
into the
of Python
and it,
thesize
know-how
toits
puttitle.
it to work.

>>> from javax.swing import JFrame


>>> frame = JFrame()
>>> frame.show()

777

>>> frame.size
= 200,200
Python
Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython

Set the title to "Hello


JFC".Hightower
By Richard

>>> frame.title = "Hello JFC"

Publisher: Addison Wesley


Pub Date: June 28, 2002

Setting the Frame'sISBN:


Mouse
Cursor
0-201-61616-5

Table of
Contents

Pages: 640

With a frame, as with all components, you can set the mouse cursor. You'll probably want to make the cursor
wait during a long operation
so it shows
a wristwatch
or hourglass
that lets
theconcise
user know
the Python
application
Characterized
by ease
of use, richness
of expression,
and
syntax,
has is busy.
In the example that follows,
set theprogramming
cursor to WAIT
,TEXT,for
andmore
HAND
. After
each and
command,
the
remainedwe'll
a premier
language
than
a decade,
is usedposition
by
mouse over the middle
of theand
frame,
and note the
image
the pointeritsbecomes.
novices
professionals
alike.
In particular,
close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
ImportCursor from java.awt, and change the cursor three times.
application development.

>>>
>>>
>>>
>>>

from java.awt
import Cursor
This tutorial begins with coverage of some of the basics of Python programming. Using
frame.setCursor(Cursor.WAIT_CURSOR)
plenty of skill-building exercises and interactive programming sessions, this book will
frame.setCursor(Cursor.TEXT_CURSOR)
help those new to programming develop an understanding of concepts and practical
frame.setCursor
= Cursor.HAND_CURSOR
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional

Adding Components
the Frame
applicationto
development.

Python Programming
withwe'll
the Java(TM)
Class
Libraries:from
A Tutorial
Building
Web and
To illustrate adding components
to the frame,
import some
components
AWT. for
Then
we'll create
and
Enterprise
Applications
with
Jython
covers
important
topics
such
as:
add a button, a label, a checkbox, and a text field.

>>> from javax.swing import JButton,


JLabel
Fundamental
programming
concepts,
including
statements, expressions,
>>> from javax.swing import JCheckBox, JTextField
interpreters, and compilers

Add a button component.

Python basics, including operators, string formatting, namespaces, classes, errors,


and exceptions
>>> frame.contentPane.add(JButton("Button"))
Add a label component.

Object-oriented programming concepts

File input/output
>>> frame.contentPane.add(JLabel("Label"))
Python's intrinsic functions
Add a checkbox component.
Formatting, parsing, and manipulating strings
>>> frame.contentPane.add(JCheckBox("Checkbox"))
Interfacing with the Java APIs and working with Java Streams
Add a text field component.
Using Python and Java Swing to create GUIs
>>> frame.contentPane.add(TextField("TextField"))
Working
SQL andsome
JDBC(TM)
You may think that our frame
shouldwith
be showing
components at this point, but it won't until we tell it to by
calling the pack() method.
Python and Java applets

>>> frame.pack()

In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

A Reminder

Doing this:

Publisher: Addison Wesley


Pub Date: June 28, 2002

>>> frame.contentPane.add(Button("Button"))
ISBN: 0-201-61616-5

Table of
Pages: 640
Contents
is equivalent to doing this:

Characterized
by ease of use, richness of expression, and concise syntax, Python has
>>> button
= Button("Button")
remained
a
premier
programming language for more than a decade, and is used by
>>> frame.contentPane.add(button)

novices and professionals alike. In particular, its close relationship to Java(TM) makes
two an
languages,
when
used inofcombination,
ideal
forit Web
distributed
The first way the
creates
anonymous
instance
Button and
adds
to theand
frame,
which isenterprise
okay
application
development.
since we don't need access to the button component for this example.
This tutorial begins with coverage of some of the basics of Python programming. Using
BorderLayout versus
plentyFrameLayout
of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques.
programmers,
theanswer
book demonstrates
Python's
breadth
of for
Only the last component
added toFor
theexperienced
frame shows
up. Why? The
lies in the default
layout
manager
FrameBorderLayout
laysthe
outways
components
along
the borders.
won'tAPIs
go into
detail about
capabilitieswhich
and shows
that Python
interfaces
withIJava
for professional
BorderLayout application
here (see Chapter
14 for that). Suffice it to say that we need to change to another manager,
development.
FlowLayout, which arranges the components from left to right as long as there's room.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
I'll tell you more about
later. Forwith
now,Jython
we'll covers
import important
the FlowLayout
andFlowLayout
Enterprise Applications
topics suchclass
as: from the java.awt
package and set the frame's layout property to a FlowLayout instance. Then we'll pack the frame, that is,
invoke the layout manager.
Fundamental programming concepts, including statements, expressions,
compilers
>>> from java.awtinterpreters,
importand
FlowLayout

>>> frame.contentPane.layout = FlowLayout()


>>> frame.pack() Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
Now all of the added components are visible.
Object-oriented programming concepts

JFrame's Lineage File input/output


intrinsic
functions
JFC frames work much likePython's
AWT frames
because
they're both cut from the same cloth. Let's examine
JFrame's lineage, which is easy to do from the interactive interpreter.
Formatting, parsing, and manipulating strings
ImportJFrame from javax.swing.
Interfacing with the Java APIs and working with Java Streams

>>> from javax.swing import JFrame


Using Python and Java Swing to create GUIs
Print out JFrame's superclass, which is java.awt.Frame.
Working with SQL and JDBC(TM)

>>> print `JFrame.superclass`


Python andat
Java227114466>
applets
<jclass java.awt.Frame
In addition,
the book
contains
instructions
This tells us that Frame
is an AWT
frame.
(Follow
along.) for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
>>> import java.awt.Frame

>>> JFrame.superclass is java.awt.Frame


Whether you are a sophisticated computer user new to programming or a serious
1
application developer, Python Programming with the Java(TM) Class Libraries will
give youbetween
insight Frame
into the power
of Python
andexample,
the know-how
to to
putadd
it toa work.
There are some differences
and JFrame
. For
if you try
component to
JFrame you get an exception. That's because components can be added only to JFrame's content pane.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

JFrame's Design Flaw

Publisher:
Addison Wesley
One of the key benefits
of inheritance
is polymorphism, so you might think we could replace
Frame with JFrame
whenever
possible.
Pub Date:
June 28,
2002 That's not the case, however. According to the Java
API Documentation,ISBN:
JFrame
and java.awt.Frame are not fully compatible.
0-201-61616-5

Table of
Contents

Pages: 640

In my opinion, making JFrame'sadd() method throw an exception is a design flaw. Its correct
behavior should
be to add the
the content
pane and then
separate
methods
Characterized
bycomponent
ease of use,torichness
of expression,
and have
concise
syntax,
Python for
has
adding it directly
to JFrame
. Instead,
by redefining
the semantics
and afunction
add()
remained
a premier
programming
language
for more than
decade,of
and
is used, the
by
developers broke
the contract
of Frame
's interface.
novices
and professionals
alike.
In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
The key to working with JFrame is not to do this:
application development.

jframe.add(component)
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
but to do this:
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
frame.contentPane.add(child);
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.

Handling Events with JFrame

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
SinceFrame is a subclass of java.awt.Frame, which is a subclass of java.awt.Window, you can
listen for window events with its event mechanism. Import the jinfo class to inspect the event properties of
Frame (JFrame's superclass).
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers

>>> import jinfo


>>> from java.awtPython
import
basics, Frame
including operators, string formatting, namespaces, classes, errors,
>>> jinfo.getEventsInfo(Frame)
and exceptions
[]
Object-oriented programming concepts
As you can see, Frame has no event properties, because its events are defined from its base class,
java.awt.Window. File input/output
Python's intrinsic functions
>>> Frame.superclass
<jclass java.awt.Window at 228949474>
Formatting, parsing, and manipulating strings
Therefore, we need to inspect Window's event properties.
Interfacing with the Java APIs and working with Java Streams

>>> jinfo.getEventsInfo(Window)
Using windowIconified
Python and Java Swing tofor
createevent
GUIs interface
[<beanEventProperty
java.awt.event.WindowListener at 861240813>, <beanEventProperty
Working
with SQL
and JDBC(TM)
WindowActivated for
event
interface
java.awt.event.WindowListener at
863600109>, <beanEventProperty
windowClosing
for event interface
Python and Java applets
java.awt.event.WindowListener at 862551533>, <beanEventProperty windowClosed
for event interface
java.awt.event.WindowListener
atinstalling
862813677>,
In addition, the
book contains instructions for downloading and
the Python
<beanEventProperty
windowDeiconified
for
event
interface
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
java.awt.event.WindowListener
and numerous code samples make this book a useful learning experience.
at 861502957>, <beanEventProperty windowOpened for event interface
java.awt.event.WindowListener
at computer
860978669>,
Whether you are a sophisticated
user new to<beanEventProperty
programming or a serious
windowDeactivated
for
eventPython
interface
java.awt.event.WindowListener
at
application
developer,
Programming
with the Java(TM) Class Libraries will
862289389>] give you insight into the power of Python and the know-how to put it to work.
There's a lot of them. I've done a little formatting to make them more readable.

777

[<... windowIconified for event interface java.awt.event.WindowListener ...>,

<... WindowActivated
for event
interface
...>,
Python Programming
with the
Java Classjava.awt.event.WindowListener
Libraries: A Tutorial for Building
<... windowClosing
for event
interface
java.awt.event.WindowListener ...>,
Web and Enterprise
Applications
with Jython
<... windowClosed
event interface java.awt.event.WindowListener ...>,
By Richardfor
Hightower
<... windowDeiconified for event interface java.awt.event.WindowListener ...>
<... windowOpened
forAddison
event
interface java.awt.event.WindowListener ...>,
Publisher:
Wesley
<... windowDeactivated
for
event
interface java.awt.event.WindowListener
Pub Date: June 28, 2002
...>]
ISBN: 0-201-61616-5

Table of

Pages: 640

NoticeContents
that the getEventsInfo() function extracts all of the information needed to work with event
properties, but it's a little hard to read. Here's an easier way.
Characterized by ease of use, richness of expression, and concise syntax, Python has
a premier
programming language
for more than a decade, and is used by
Import all of jinforemained
and import
java.awt.Window
.
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two
languages,
>>> from jinfo
import
* when used in combination, ideal for Web and distributed enterprise
application
development.
>>> from java.awt import Window

This tutorial
begins
with coverage
of some
of thefrom
basics
of Python
Use getEventsInfo()
to get
the sequence
of event
properties
Window
. programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
>>> eProps = help
getEventsInfo(Window)
those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
Use len() to determine
how many
properties
there that
are. Python interfaces with Java APIs for professional
capabilities
and shows
the ways
application development.

>>> print `len(eProps)`


7
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web

and Enterprise Applications with Jython covers important topics such as:
Once you know how many properties there are, invoke printEventProperty() to print out details
about the event.
Fundamental programming concepts, including statements, expressions,
>>> printEventProperty(eProps[0])
interpreters, and compilers

Event Property:
windowOpened
Defined in:
java.awt.event.WindowListener
Python basics, including
operators, string formatting, namespaces, classes, errors,
Event:
java.awt.event.WindowEvent
and exceptions
Event properties for java.awt.event.WindowEvent:
Object-oriented
programming
concepts
window
Type:
org.python.core.PyBeanProperty
Public Event fields for java.awt.event.WindowEvent:
input/output
static finalFileWINDOW_FIRST
Type: int
static final WINDOW_LAST
Type: int
Python's intrinsic functions
static final WINDOW_OPENED
Type: int
static finalFormatting,
WINDOW_CLOSING
Type: int
parsing, and manipulating strings
static final WINDOW_CLOSED
Type: int
static finalInterfacing
WINDOW_ICONIFIED
Type:
with the Java APIs and working
with int
Java Streams
static final WINDOW_DEICONIFIED
Type: int
Python and Java Swing to createType:
GUIs int
static finalUsing
WINDOW_ACTIVATED
Working
with
JDBC(TM)
printEventProperty()
tells
youSQL
threeand
important
things:
Python and Java applets
The name of the interface that defines the listenerjava.awt.event.WindowListener
In addition, the book contains instructions for downloading and installing the Python
The name of the
class that
theDevelopment
event object Kit
passed
to the
language
anddefines
the Java
(JDK).
Terminology, definitions, explanations,
listenerjava.awt.event.WindowEvent
and numerous code samples make this book a useful learning experience.
The propertiesWhether
and fields
with the event
objectuser new to programming or a serious
youassociated
are a sophisticated
computer
application developer, Python Programming with the Java(TM) Class Libraries will
Let's look at windowDeactivated
give you insight into:the power of Python and the know-how to put it to work.

>>> printEventProperty(eProps[6])
Event Property:
windowDeactivated
Defined in:
java.awt.event.WindowListener

777

Event:
Python Programming java.awt.event.WindowEvent
with the Java Class Libraries: A Tutorial for Building
Event properties
for
java.awt.event.WindowEvent:
Web and
Enterprise
Applications with Jython
window ByRichard Hightower
Type: org.python.core.PyBeanProperty
Public Event fields for java.awt.event.WindowEvent:
static final
WINDOW_FIRST
Type: int
Publisher:
Addison Wesley
static final
WINDOW_LAST
Type: int
Pub Date: June 28, 2002
static finalISBN:
WINDOW_OPENED
Type: int
0-201-61616-5
Table
of
static
final
WINDOW_CLOSING
Type: int

Pages: 640
Contents
static final WINDOW_CLOSED
Type: int
static final
WINDOW_ICONIFIED
Type:and
int
Characterized by ease of use, richness of expression,
concise syntax, Python has
static final
WINDOW_DEICONIFIED
Type:
int
remained a premier programming language for more than
a decade, and is used by
static final
WINDOW_ACTIVATED
int
novices and
professionals alike. In particular, Type:
its close relationship
to Java(TM) makes
static final
WINDOW_DEACTIVATED
the two languages,
when used in combination,Type:
ideal forint
Web and distributed enterprise
application development.
You might want to look up the rest of the event properties and traverse Frame's lineage until you reach a
superclass called Object
.
This tutorial
begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
programmers, the book demonstrates Python's breadth of
Twotechniques.
Ways For
to experienced
Look Up
Events with One Method
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
This one works best on Windows 98 because it pauses after each event:
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
>>> import
jinfo Applications with Jython covers important topics such as:
and Enterprise

>>> from java.awt import Window


>>> jinfo.getEventsInfo(Window, 1, 1)
Fundamental programming concepts, including statements, expressions,
This one works bestinterpreters,
on Windowsand
NTcompilers
because you can scroll the DOS box to see the results:

>>> import jinfo


Python basics, including operators, string formatting, namespaces, classes, errors,
>>> from java.awt
import Window
and exceptions
>>> jinfo.getEventsInfo(Window, 1)
Object-oriented programming concepts
File input/output
Python's intrinsic functions
Table 13-1. Frame, JFrame, and Window Events
Formatting, parsing, and manipulating strings
windowOpened(WindowEvent e)
The window is first opened.
Interfacing with the Java APIs and working with Java Streams
windowClosed(WindowEvent e)
The window is closed.
Using Python ande)
Java Swing
to create
GUIs
windowClosing(WindowEvent
The user
is requesting
to close the windowa good
time to see if the user wants to save any unsaved data.
Working with SQL e)
and JDBC(TM)
windowActivated(WindowEvent
The window is the active window; the window or one of
its contained components have the keyboard focus.
Python and Java applets
windowDeactivated(WindowEvent The window doesn't have keyboard focus.
e)
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development
Kit when
(JDK).the
Terminology,
windowIconified(WindowEvent
e) Invoked
window is definitions,
minimized.explanations,
and
numerous
code
samples
make
this
book
a
useful
learning
experience.
windowDeiconified(WindowEvent The window has been restored to its size before it was
iconified.
e)
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
Table 13-1 lists and describes the events supported by Frame,JFrame, and Window. All of the event
give you insight into the power of Python and the know-how to put it to work.
properties have a one-to-one correspondence to a method in their listener interface.

777

Event Handling for Frame and JFrame

The following example


demonstrates
Java event
for both
JFrame
andA Frame
. Itfor
also
shows how to
Python
Programming
withhandling
the Java
Class
Libraries:
Tutorial
Building
treat the two classes Web
polymorphically.
and Enterprise Applications with Jython
By Richard Hightower

Create a Listener class by extending the java.awt.event.WindowListener interface.


Publisher: Addison Wesley

from java.awt.event import WindowListener


Pub Date: June 28, 2002

ISBN: 0-201-61616-5
class
Listener
(WindowListener):
Table
of

Pages:
640
def windowOpened(self,
windowEvent):
Contents
self.handleEvent("windowOpened",windowEvent)
Characterized by ease of use,
richness of expression, and concise syntax, Python has
def windowClosed(self,
windowEvent):
remained
a
premier
programming
language for more
than a decade, and is used by
self.handleEvent("windowClosed",
windowEvent)
novices
and
professionals
alike.
In
particular,
its
close
relationship to Java(TM) makes
def windowClosing(self, windowEvent):
the
two
languages,
when
used
in
combination,
ideal
for
Web and distributed enterprise
self.handleEvent("windowClosing",windowEvent)
application
development.
def WindowActivated(self, windowEvent):
self.handleEvent("WindowActivated", windowEvent)
This tutorial begins with coverage of some of the basics of Python programming. Using
def windowDeactivated(self, windowEvent):
plenty of skill-building exercises and interactive programming sessions, this book will
self.handleEvent("windowDeactivated", windowEvent)
help those new to programming develop an understanding of concepts and practical
def windowIconified(self, windowEvent):
techniques. For experienced programmers, the book demonstrates Python's breadth of
self.handleEvent("windowIconified", windowEvent)
capabilities and shows the ways that Python interfaces with Java APIs for professional
def windowDeiconified(self, windowEvent):
application development.
self.handleEvent("windowDeiconified", windowEvent)
def handleEvent(self,
event_name,
event):
Python Programming with
the Java(TM) Class
Libraries: A Tutorial for Building Web
print
"Event:
"
+
event_name
and Enterprise Applications with Jython covers important topics such as:
print "Event info: " + `event.class`
print "Source: " + `event.source.title`
Fundamental programming concepts, including statements, expressions,
print "----------------"

interpreters, and compilers


Python basics, including
operators, string formatting, namespaces, classes, errors,
Adapters
and exceptions
In the Listener Object-oriented
code example, we
were interested
in all methods, so we used
programming
concepts
WindowListener. To save time you can derive the listener from WindowAdapter and
only override the events
that interest you.
File input/output
All listener classes have
corresponding
adapter classes. The best way to know if a particular event
Python's
intrinsic functions
listener interface has a corresponding event listener class is to check the Java API documentation.
Formatting, parsing, and manipulating strings
Essentially we've created a class that implements java.awt.event.WindowListener. We handle
Interfacing with the Java
APIswhich
and working
with
Streams
every event by calling the handleEvent()
method,
prints out
theJava
event
name, a string denoting
which event occurred, the name
of
the
event
class
that
contains
information
regarding
the event, and the source's
Using Python and Java Swing to create GUIs
title property.
Working with SQL and JDBC(TM)
Now we'll create two frames, javax.swing.JFrame and java.awt.Frame. Then we'll pass an
instance of the listener class
(listener
with addWindowListener to register the event listener with
Python
and Java) applets
the event source. To create and set up the frames, I've created a function called createFrame(), which
takes a class and a title
as arguments.
CreateFrame()
usesforthedownloading
class to create
instance the
of Frame
In addition,
the book
contains instructions
andaninstalling
Python and
then sets its size, title,
and visibility.
reason
we can use
that, JFrame
being
language
and theThe
Java
Development
KitcreateFrame()
(JDK). Terminology,isdefinitions,
explanations,
derived from Frame
, both
implement
same interface.
and
numerous
codethe
samples
make this book a useful learning experience.
Here's the createFrame()
(from WindowEventListener.py).
Whether youmethod
are a sophisticated
computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
def createFrame(clazz,
title,
listener):
give you insight into
the power
of Python and the know-how to put it to work.

frame = clazz()
frame.addWindowListener(listener)
frame.setSize(200, 200)
frame.setTitle(title)

777

frame.setVisible(1)
Python Programming with the Java Class Libraries: A Tutorial for Building
return frame
Web and Enterprise Applications with Jython
By Richard Hightower

Note that the call to addWindowListener registers an instance of the Listener class with a frame.
Publisher: Addison Wesley

Now we'll use the createFrame() function to create both a Frame and a JFrame.
Pub Date: June 28, 2002

ISBN: 0-201-61616-5
fromTable
java.awt
import
Frame
of

Pages:
640
fromContents
javax.swing import JFrame
...
Characterized by ease of use, richness of expression, and concise syntax, Python has
...
a premier programming language for more than a decade, and is used by
listenerremained
= Listener()

novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two
languages,Enter
when used
combination,
Web and distributed enterprise
raw_input
("Press
toincreate
a ideal
JFC for
Frame")
application
development.
jfc_frame = createFrame(JFrame, "JFC Frame", listener)
This("Press
tutorial begins
with coverage
of some of
basicsFrame")
of Python programming. Using
raw_input
Enter
to create
antheAWT
plenty
of
skill-building
exercises
and
interactive
programming
sessions, this book will
awt_frame = createFrame(Frame, "AWT Frame", listener)

help those new to programming develop an understanding of concepts and practical


techniques.
For experienced
the book
breadthfrom
of both.
Since the same listener
instance
is registeredprogrammers,
with both Frame
anddemonstrates
JFrame, itPython's
will get events
capabilities and shows the ways that Python interfaces with Java APIs for professional
Run the WindowEventListener
class and, when it asks you to "Press Enter to create a JFC Frame," do
application development.
so. You should see the following in the DOS box:
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
Event: WindowActivated
and Enterprise Applications with Jython covers important topics such as:

Event info: <jclass java.awt.event.WindowEvent at 1384027101>


Source: 'JFC Frame'
----------------Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
Event: windowOpened
Event info: <jclass java.awt.event.WindowEvent at 1384027101>
Python basics, including operators, string formatting, namespaces, classes, errors,
Source: 'JFC Frame'
and exceptions
----------------
Object-oriented programming concepts
When the window is first created, it sends the WindowActivated and windowOpened events.
File input/output
Now return to where you ran the script; you should get the following message:
Python's intrinsic functions

Event info: <jclass java.awt.event.WindowEvent at 1384027101>


Source: 'JFC Frame'
Formatting, parsing, and manipulating strings
----------------
Interfacing with the Java APIs and working with Java Streams
As you can see, the JFC frame is no longer active, so it sends out a windowDeactivated event.
Using Python and Java Swing to create GUIs
Now that the DOS box is the active window, hit Return. You should get the following messages:
Working with SQL and JDBC(TM)

Event: WindowActivated
Event info: <jclass
at 1408756942>
Pythonjava.awt.event.WindowEvent
and Java applets
Source: 'AWT Frame'
In addition, the book contains instructions for downloading and installing the Python
----------------
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
Event: windowOpened
and numerous
code samples make this book a useful learning
experience.
Event info: <jclass
java.awt.event.WindowEvent
at 1408756942>
Source: 'AWT Frame'
Whether you are a sophisticated computer user new to programming or a serious
----------------
application developer, Python Programming with the Java(TM) Class Libraries will
give
of Python
andSelect
the know-how
totimes
put it(by
to work.
Move the AWT frame
so you
thatinsight
you caninto
seethe
thepower
JFC frame
as well.
each a few
clicking once on
their individual captions). As you go from one to the other, you should get the following messages:

777

Event: windowDeactivated
Event info: <jclass java.awt.event.WindowEvent

Source: 'JFC Python


Frame'
Programming with the Java Class Libraries: A Tutorial for Building
----------------
Web and Enterprise Applications with Jython
Event: WindowActivated
By Richard Hightower
Event info: <jclass java.awt.event.WindowEvent
Source: 'AWT Frame'
Publisher: Addison Wesley
----------------
Pub Date: June 28, 2002
Event: windowDeactivated
ISBN: 0-201-61616-5
Table
of
Event
info:
<jclass
java.awt.event.WindowEvent

Pages: 640
Contents
Source:
'AWT Frame'
----------------
Characterized by ease of use, richness of expression, and concise syntax, Python has
Event: WindowActivated
remained a premier programming language for more than a decade, and is used by
Event info: <jclass
java.awt.event.WindowEvent
novices and professionals
alike. In particular, its close relationship to Java(TM) makes
Source: 'JFC the
Frame'
two languages, when used in combination, ideal for Web and distributed enterprise
----------------
application development.
If you minimize the JFC
should
these messages
This frame,
tutorialyou
begins
withgetcoverage
of some inofthe
theDOS
basicsbox:
of Python programming. Using

plenty of skill-building exercises and interactive programming sessions, this book will

Event: windowIconified
help those new to programming develop an understanding of concepts and practical
Event info: <jclass java.awt.event.WindowEvent
techniques. For experienced programmers, the book demonstrates Python's breadth of
Source: 'JFC Frame'
capabilities and shows the ways that Python interfaces with Java APIs for professional
----------------
application development.
Event: windowDeactivated
Event info: <jclass
java.awt.event.WindowEvent
Python Programming
with the Java(TM) Class Libraries: A Tutorial for Building Web
Source: 'JFC and
Frame'
Enterprise Applications with Jython covers important topics such as:
----------------
Event: WindowActivated
Fundamental
programming concepts, including statements, expressions,
Event info: <jclass
java.awt.event.WindowEvent
interpreters, and compilers
Source: 'AWT Frame'
----------------
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
When the JFC frame is minimized,
it sends out a windowIconified event followed by a
windowDeactivated event. Since the AWT frame was the last active window, it becomes the active
Object-oriented
programmingevent.
concepts
window again and sends out
a WindowActivated
If you can maximize the JFC frame, you'll get the
following messages:
File input/output

Event: windowDeactivated
Python's
intrinsic functions
Event info: <jclass
java.awt.event.WindowEvent
Source: 'AWT Frame'
Formatting, parsing, and manipulating strings
----------------
Event: WindowActivated
Interfacing with the Java APIs and working with Java Streams
Event info: <jclass java.awt.event.WindowEvent
Source: 'JFC Frame'
Using Python and Java Swing to create GUIs
----------------
Working with SQL and JDBC(TM)
Event: windowDeiconified
Event info: <jclass java.awt.event.WindowEvent
Python and Java applets
Source: 'JFC Frame'
----------------

In addition, the book contains instructions for downloading and installing the Python
Development
Kit (JDK).
Terminology,
definitions,
explanations,
First the AWT framelanguage
and thenand
the the
JFCJava
frame
are deactivated;
then the
JFC frame sends
a
and
numerous
code
samples
make
this
book
a
useful
learning
experience.
windowDeactivated event. Close the JFC frame by clicking on its close control (on Windows 95/98/NT,
it's an X in the top right corner next to the caption). You should get the following messages:
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
Event: windowClosing
give you insight
into the power of Python and the know-how to put it to work.
Event info: <jclass
java.awt.event.WindowEvent

Source: 'JFC Frame'


----------------
Event: windowDeactivated
Event info: <jclass java.awt.event.WindowEvent

777

Source: 'JFC Python


Frame'
Programming with the Java Class Libraries: A Tutorial for Building
----------------
Web and Enterprise Applications with Jython
Event: WindowActivated
By Richard Hightower
Event info: <jclass java.awt.event.WindowEvent
Source: 'AWT Frame'
Publisher: Addison Wesley
----------------
Pub Date: June 28, 2002
ISBN: 0-201-61616-5

Table
of
Now try
to close
the AWT frame using the same technique. What happens? Why?
Contents

Pages: 640

The JFC frame's default method of closing a window is hiding the frame. Since the AWT frame doesn't handle
Characterized
easetoofadd
use,
richnessand
of expression,
and concise syntax, Python has
thewindowClosing
event, youby
have
a handler
do it yourself.
remained a premier programming language for more than a decade, and is used by
novices and
professionals alike. In particular,
its close
to Java(TM)
Unlike java.awt.Frame
,javax.swing.JFrame
responds
whenrelationship
a user attempts
to close amakes
window.
the
two
languages,
when
used
in
combination,
ideal
for
Web
and
distributed
enterprise
You can change the default behavior (hiding the frame) by invoking the
application development.
setDefaultCloseOperation()
method to make the frame exit the application. Look this up, as well
as other default operation-closing methods, in the Java API documentation.
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
The Complete Java Event-Handling Code
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
Here's the complete listing (WindowEventListener.py) for the Java way of handling events:
capabilities and shows the ways that Python interfaces with Java APIs for professional
from java.awtapplication
importdevelopment.
Frame

from javax.swing import JFrame


Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
from java.awt.event import WindowListener
and Enterprise Applications with Jython covers important topics such as:
class Listener (WindowListener):
def windowOpened(self, windowEvent):
self.handleEvent("windowOpened",windowEvent)
Fundamental programming concepts, including statements, expressions,
def windowClosed(self,
windowEvent):
interpreters, and compilers
self.handleEvent("windowClosed", windowEvent)
Python basics, including
operators, string formatting, namespaces, classes, errors,
def windowClosing(self,
windowEvent):
and exceptions
self.handleEvent("windowClosing",windowEvent)
def WindowActivated(self, windowEvent):
Object-oriented programming concepts
self.handleEvent("WindowActivated",
windowEvent)
def windowDeactivated(self, windowEvent):
File input/output
self.handleEvent("windowDeactivated",
windowEvent)
def windowIconified(self,
windowEvent):
Python's intrinsic functions
self.handleEvent("windowIconified", windowEvent)
def windowDeiconified(self,
windowEvent):
Formatting, parsing, and manipulating
strings
self.handleEvent("windowDeiconified", windowEvent)
def handleEvent(self,
event_name,
event):
Interfacing with the
Java APIs and working
with Java Streams
print "Event: " + event_name
Using Python
and Java
to create GUIs
print "Event
info:
" Swing
+ `event.class`
print "Source: " + `event.source.title`
withProperties:
SQL and JDBC(TM)
#print Working
"Event
" + `dir(event)`
print "----------------"
Python and Java applets

def createFrame(clazz,
title,
listener):
In addition, the book contains
instructions
for downloading and installing the Python
frame
=
clazz()
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
frame.addWindowListener(listener)
and numerous code samples make this book a useful learning experience.
frame.setSize(200, 200)
frame.setTitle(title)
Whether you are a sophisticated computer user new to programming or a serious
frame.setVisible(1)
application developer, Python Programming with the Java(TM) Class Libraries will
return
give youframe
insight into the power of Python and the know-how to put it to work.
def main():
listener = Listener()

777

raw_input
("Press with
Enter
to create
a JFCA Tutorial
Frame")
Python Programming
the Java
Class Libraries:
for Building
jfc_frame
= createFrame(JFrame,
"JFC Frame", listener)
Web and Enterprise
Applications with Jython
raw_input
("Press Enter to create an AWT Frame")
By Richard Hightower
awt_frame = createFrame(Frame, "AWT Frame", listener)
Publisher: Addison Wesley

if __name__
== "__main__":
Pub Date:
June 28, 2002
main() ISBN: 0-201-61616-5

Table of
Contents

Pages: 640

The Python Way of Handling Events

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
The following brief interactive session highlights the Python way of handling events:
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
>>> def closing(event):
development.
...
printapplication
"windowClosing"

...
This tutorial begins with coverage of some of the basics of Python programming. Using
>>> def closed(event):
of skill-building exercises and interactive programming sessions, this book will
...
printplenty
"windowClosed"
help
those
new to programming develop an understanding of concepts and practical
...
techniques.
>>> def open(event):For experienced programmers, the book demonstrates Python's breadth of
and shows the ways that Python interfaces with Java APIs for professional
...
printcapabilities
"windowOpened"
application development.
...
PythonanProgramming
Java(TM)
Libraries: A Tutorial for Building Web
Import a JFrame, create
instance of it,with
andthe
configure
the Class
instance.
and Enterprise Applications with Jython covers important topics such as:

>>>
>>>
>>>
>>>

from javax.swing import JFrame


frame = JFrame()
Fundamental programming concepts, including statements, expressions,
frame.title =interpreters,
"JFrame
frame"
and compilers
frame.size = 200,200

Python basics, including operators, string formatting, namespaces, classes, errors,


Set the event properties of and
the frame
to the functions created.
exceptions

>>> frame.windowClosing
= closing
Object-oriented programming concepts
>>> frame.windowClosed = closed
>>> frame.windowOpened
= open
File input/output
Notice that the event properties
windowClosing
Python's
intrinsic functions,windowClosed, and windowOpened correspond
to the methods in the java.awt.WindowListener interface. Show the window for the first time to get
thewindowOpened event.
Formatting, parsing, and manipulating strings

>>> frame.visibleInterfacing
= 1 with the Java APIs and working with Java Streams
windowOpened
Using Python and Java Swing to create GUIs
Close the frame using the Close button in the upper right corner to get the DOS box message.
Working with SQL and JDBC(TM)

windowClosing
Python and Java applets
Make the frame visible again. (You don't get another windowOpened event; that happens only when the
In addition,
thetime.)
book contains instructions for downloading and installing the Python
frame becomes visible
for the first
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
>>> frame.visible
= 1 code samples make this book a useful learning experience.
and numerous
Call the frame's dispose()
method
to actually close
the window.
You'll
get a windowClosed
Whether you
are a sophisticated
computer
user new
to programming
or a serious event.
application developer, Python Programming with the Java(TM) Class Libraries will
>>> frame.dispose()
give you insight into the power of Python and the know-how to put it to work.

windowClosed

777

As you can see, for just a few events you can define just a few event handlers and assign them to the event
property of the frame instance. The event properties always correspond to the event listener's methods.

Python Programming with the Java Class Libraries: A Tutorial for Building
Python's WindowEventListener
Web and Enterprise Applications with Jython
By Richard Hightower

The following example illustrates the same functionality as in the WindowEventListener.py module, except that
everything is written using Python event properties and handlers instead of the more Java-centric way of doing
Publisher: Addison Wesley
things. Read the code, and
see if you can pick out the differences.
Pub Date: June 28, 2002

ISBN: 0-201-61616-5
from java.awt import
Frame
Table of

from
javax.swing
import
Pages:
640 JFrame
Contents

Characterized by ease of use, richness of expression, and concise syntax, Python has
def windowOpened(windowEvent):
remained a premier programming language for more than a decade, and is used by
handleEvent("windowOpened",windowEvent)
novices and professionals alike. In particular, its close relationship to Java(TM) makes
def windowClosed(windowEvent):
the two languages, when used in combination,
ideal for Web and distributed enterprise
handleEvent("windowClosed",
windowEvent)
application
development.
def windowClosing(windowEvent):
handleEvent("windowClosing",windowEvent)
This tutorial begins with coverage of some of the basics of Python programming. Using
def WindowActivated(windowEvent):
plenty of skill-building exercises and interactive
programming sessions, this book will
handleEvent("WindowActivated",
windowEvent)
help
those
new
to
programming
develop
an
understanding
of concepts and practical
def windowDeactivated(windowEvent):
techniques.
For
experienced
programmers,
the
book
demonstrates
Python's breadth of
handleEvent("windowDeactivated", windowEvent)
capabilities
and
shows
the
ways
that
Python
interfaces
with
Java
APIs
for professional
def windowIconified(windowEvent):
application development.
handleEvent("windowIconified",
windowEvent)
def windowDeiconified(windowEvent):
Python Programming with the Java(TM) Class
Libraries: A Tutorial for Building Web
handleEvent("windowDeiconified",
windowEvent)
and
Enterprise
Applications
with
Jython
covers
important topics such as:
def handleEvent(event_name, event):
print "Event: " + event_name
print "EventFundamental
info: "programming
+ `event.class`
concepts, including statements, expressions,
print "Source:
"
+
`event.source.title`
interpreters, and compilers
#print "Event Properties: " + `dir(event)`
print "----------------"
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions

def createFrame(clazz, title):


Object-oriented programming concepts
frame = clazz()
File input/output
frame.windowClosing
= windowClosing
frame.windowOpened = windowOpened
Python's intrinsic functions
frame.windowClosed = windowClosed
frame.windowIconified
= and manipulating
windowIconified
Formatting, parsing,
strings
frame.windowDeiconified = windowDeiconified
frame.WindowActivated
= Java
WindowActivated
Interfacing with the
APIs and working with Java Streams
frame.windowDeactivated = windowDeactivated
Using Python and Java Swing to create GUIs

frame.size = 200, 200


with SQL and JDBC(TM)
frame.title Working
= title
frame.visible = 1
return framePython and Java applets
def main():

In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.

raw_input ("Press Enter to create a JFC Frame")


jfc_frame
= createFrame(JFrame,
"JFC
Frame")
Whether
you are a sophisticated computer
user new
to programming or a serious

application developer, Python Programming with the Java(TM) Class Libraries will

raw_input
Enter
to ofcreate
antheAWT
Frame")
give ("Press
you insight into
the power
Python and
know-how
to put it to work.
awt_frame = createFrame(Frame, "AWT Frame")

777

if __name__ == "__main__":
main()

I find myself using the


PythonProgramming
way more often
thanthe
theJava
Java way,
mainly
because
have to import
fewer classes
Python
with
Class
Libraries:
A ITutorial
for Building
and have to remember
only
theEnterprise
name of theApplications
event handler,with
not every
method in the listener.
Web
and
Jython
By Richard Hightower

The Class Hierarchy for JFrame and Frame


Publisher: Addison Wesley
Pub Date: June 28, 2002

For review, let's cover the class hierarchy of JFrame and then Frame. Start up the interactive interpreter and
ISBN: 0-201-61616-5
followTable
along.ofTo get the superclass of JFrame, import JFrame, and then inspect its superclass property.

Contents

Pages: 640

>>> from javax.swing import JFrame


Characterized by ease of use, richness of expression, and concise syntax, Python has
>>> JFrame.superclass
remained a premier
language for more than a decade, and is used by
<jclass java.awt.Frame
atprogramming
214168159>
novices and professionals alike. In particular, its close relationship to Java(TM) makes
two languages,
usedsuperclass
in combination,
idealsuperclass
for Web and distributed
enterprise
To find out Frame'sthe
superclass,
appendwhen
another
to it. Since
is an instance
of
application
development.
jclass and jclass has the property superclass, we can get the superclass of JFrame's superclass
like this:
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
>>> JFrame.superclass.superclass
help those new to programming
develop an understanding of concepts and practical
<jclass java.awt.Window
at 217313887>
techniques. For experienced programmers, the book demonstrates Python's breadth of
We can continue to do
this until and
we hit
Object
. that Python interfaces with Java APIs for professional
capabilities
shows
the ways
application development.

>>> JFrame.superclass.superclass.superclass
<jclass java.awt.Container
atthe219411039>
Python Programming with
Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

>>> JFrame.superclass.superclass.superclass.superclass
<jclass java.awt.Component at 221770335>
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
>>> JFrame.superclass.superclass.superclass.superclass.superclass

<jclass java.lang.Object at -1247546800>

Python basics, including operators, string formatting, namespaces, classes, errors,


exceptions language classes can only singly inherit from a superclass, so they
Unlike Python classes, Javaand
programming
have a narrow chain of superclasses. JFrame's class hierarchy looks like this:
Object-oriented programming concepts

Object

Component

Container

File input/output

Window

Frame

Window

Frame

JFrame

Frame's class hierarchy looks like this:

Python's intrinsic functions

Object

Component

Container

Formatting, parsing, and manipulating strings

What's revealed is that JFrame and Frame inherit functionality from Container,Component, and
Interfacing with the Java APIs and working with Java Streams
Window. To find out more about these base classes and how they relate to JFrame and Frame, look them
up in the Java API documentation.
Using Python and Java Swing to create GUIs

Working with
SQL and JDBC(TM)
Component Functionality
Inherited
from JFrame and Frame
Python
and Javathat
applets
Now let's look at some of the
functionality
JFrame and Frame get from Component. As always,
follow along. CreateIna frame.
addition, the book contains instructions for downloading and installing the Python
language and the
Java Development
>>> from javax.swing
import
JFrame Kit (JDK). Terminology, definitions, explanations,
and
numerous
code
samples
make this book a useful learning experience.
>>> frame = JFrame()
>>> frame = JFrame(visible=1,
size=(200,200))
Whether you are a sophisticated computer user new to programming or a serious
developer,
Python
withscreen.
the Java(TM) Class Libraries will
FromComponentapplication
comes the ability
to move
the Programming
frame around the
give you insight into the power of Python and the know-how to put it to work.

>>> from javax.swing import JFrame


>>> frame = JFrame()
>>> frame = JFrame(visible=1, size=(200,200))

777

Thebounds() method
takes
four arguments:
thethe
x and
y positions
of the upper
left cornerfor
of Building
the frame and
Python
Programming
with
Java
Class Libraries:
A Tutorial
the frame's width andWeb
height.
you want toApplications
change the location
of a frame without changing its width and
andIfEnterprise
with Jython
height, use setLocation()
.
By Richard Hightower

>>> frame.setLocation(50,50)
Publisher: Addison Wesley
>>> frame.setLocation(0,0)
Pub Date: June 28, 2002
ISBN: 0-201-61616-5
The background
property from
Component allows you to change the RGB (red-green-blue) value of the
Table of

Pages: 640
frame'sContents
background.

Characterized =
by ease
of use,
>>> frame.background
(255,
0 richness
, 0) of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
novices and professionals
alike. In
>>> frame.background
= (0, 255,
0)particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
>>> frame.background
= (0, 0, 255)
This tutorial begins
with coverage
some of the basics of Python programming. Using
>>> frame.background
= (255,
255, of0)
plenty of skill-building exercises and interactive programming sessions, this book will
thoseproperties
new to programming
develop
an understanding
of concepts and practical
Here are some otherhelp
familiar
that come from
Component
:
techniques. For experienced programmers, the book demonstrates Python's breadth of
>>> frame.size
= 150,
capabilities
and 150
shows the ways that Python interfaces with Java APIs for professional
>>> frame.visible
= development.
1
application

>>> frame.visible
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
1
and Enterprise Applications with Jython covers important topics such as:

JPanel
Fundamental programming concepts, including statements, expressions,
interpreters,
compilers
Panels allow you to organize
portions ofand
a larger
user interface within a frame, a dialog, or a window. Like
frames (java.awt.Frame and javax.swing.JFrame), panels extend the
Python
basics,
operators,
formatting,
namespaces,
classes,they
errors,
java.awt.Container
class,
whichincluding
means that
they canstring
contain
other components.
However,
can't
and exceptions
exist on their own but must be in the context of a window, dialog, or frame, or in the context of another panel
contained in a top-level window (like Dialog,Frame, or Window).
Object-oriented programming concepts
Here's a JFC/Swing example of adding components with JPanel, in which every time the Add button is
File input/output
pressed another button is added to a panel. Import JPanel and JFrame from the javax.swing package.

Python's intrinsic functions

>>> from javax.swing import JPanel, JFrame, JButton


Formatting, parsing, and manipulating strings
Create a frame variable in the global space of the main module. Also, create an instance of JPanel called
pane, and initialize the count
to 0. with the Java APIs and working with Java Streams
Interfacing

>>> frame = None Using Python and Java Swing to create GUIs
>>> pane = JPanel()
>>> count = 0
Working with SQL and JDBC(TM)
Define an add() functionPython
that takes
variables pane,count, and frame into its local namespace
and the
Javaglobal
applets
and adds a button to the panel called Pane. add() also increments the count variable, which keeps track of
In added.
addition, the book contains instructions for downloading and installing the Python
how many buttons are
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
>>> def add(event):
and numerous code samples make this book a useful learning experience.

...
...
...
...
...
...
...

global pane
Whether
you are a sophisticated computer user new to programming or a serious
global
count
application
global
framedeveloper, Python Programming with the Java(TM) Class Libraries will
insight+into1 the power of Python and the know-how to put it to work.
countgive
= you
count
pane.add(JButton('Button' + `count`))
frame.pack()

777

Define a remove()
function
that removeswith
the last
method
uses the
count variable
(which is in
Python
Programming
thebutton.
JavaThis
Class
Libraries:
A Tutorial
for Building
the module namespace)
determine
the last
button removed.
Webtoand
Enterprise
Applications
with Jython
By Richard Hightower

>>> def remove(event):


...
global Publisher:
pane Addison Wesley
...
global Pub
count
Date: June 28, 2002
...
global frame
ISBN: 0-201-61616-5
... Table ofpane.remove(count-1)
Pages: 640
... Contents
count = count 1
...
frame.pack()

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained
premier
programming
language
more than
a decade,
and is
used
by a
Supply an Add button
(addB)ato
add a button
to the pane
and a for
Remove
button
(removeB
) to
remove
novices
and
professionals
alike.
In
particular,
its
close
relationship
to
Java(TM)
makes
button. The event handler for the Add button is set to the add() function.
the two languages, when used in combination, ideal for Web and distributed enterprise
application("Add",
development.actionPerformed = add)
>>> addB = JButton

>>> removeB = JButton("Remove", actionPerformed = remove)


This tutorial pane.add(removeB)
begins with coverage of some of the basics of Python programming. Using
>>> pane.add(addB);
plenty
of
skill-building
exercises and interactive programming sessions, this book will
>>> count = 2

help those new to programming develop an understanding of concepts and practical


techniques.
experienced
programmers,
book
demonstrates
Python's
breadth
of and
Create a frame, and set
its title toFor
"Panel
Demo." Set
the contentthe
pane
to the
pane instance
defined
earlier,
capabilities
and
shows
the
ways
that
Python
interfaces
with
Java
APIs
for
professional
make the frame visible.
application development.

>>> frame=JFrame(title="Panel Demo", contentPane=pane, visible=1)


Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
>>> frame.pack()
and Enterprise Applications with Jython covers important topics such as:
Hit the Add button twice to add a third and a fourth button to the panel. Hit it two more times to add a fifth and a
sixth button. Hit the Remove button twice to remove the fifth and sixth buttons. Hit the Add button a good 10 to
programming
concepts, including statements, expressions,
20 times, and then you canFundamental
resize the frame
with the mouse.
interpreters, and compilers

JLabel

Python basics, including operators, string formatting, namespaces, classes, errors,


and exceptions

Labels are components for placing text in a container. From a user perspective, they're read-only, although their
Object-oriented programming concepts
text can be changed programmatically. Let's have a short interactive session that demonstrates using
javax.swing.JLabel
.
File input/output
Import the classes needed. Python's intrinsic functions

>>> from javax.swing


import JLabel, JFrame
Formatting, parsing, and manipulating strings
Create a frame to hold the Interfacing
label.
with the Java APIs and working with Java Streams

>>> frame = JFrame(visible=1,


title="Label Demo")
Using Python and Java Swing to create GUIs
Create the label, and add itWorking
to the frame;
the frame to make the label visible.
with then
SQLpack
and JDBC(TM)

>>> label = JLabel("Hello


World")#Create a label
Python and Java applets
>>> frame.contentPane.add(label) #add the label to the frame
>>> frame.pack()
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
For this next exerciseand
wenumerous
need to resize
window
with
mouse
so welearning
can readexperience.
all of the text in the frame
code the
samples
make
thisthe
book
a useful
caption (sometimes referred to as the titlebar). You can set the alignment of the label text for center, right, or left.
Whether you are a sophisticated computer user new to programming or a serious
>>> label.horizontalAlignment
= JLabel.CENTER
application developer, Python Programming with the Java(TM) Class Libraries will
>>> label.horizontalAlignment
= JLabel.RIGHT
give you insight into the power of Python and the know-how to put it to work.

>>> label.horizontalAlignment = JLabel.LEFT

777

JComponent

JLabel is derived Python


from JComponent
, which
is full
of functionality
such asAthe
ability for
to set
an icon or
Programming
with the
Java
Class Libraries:
Tutorial
Building
tooltip to a label. TheWeb
following
example illustrates
some with
of theJython
things you can do. Import the JLabel and
and Enterprise
Applications
JFrame classes. ByRichard Hightower
>>> from javax.swing
import JLabel, JFrame
Publisher: Addison Wesley
Pub Date: June 28, 2002

Create a frame and a label; put the label in the frame's content pane.

>>>

Table of
frame
Contents

ISBN: 0-201-61616-5

Pages: 640
JFrame(visible=1,

=
title="JComponent/JLabel Demo")
>>> label = JLabel("JComponent/JLabel demo")
Characterized by ease of use, richness
of expression, and concise syntax, Python has
>>> frame.contentPane.add(label);
frame.pack()
remained a premier programming language for more than a decade, and is used by
novices
andforprofessionals
alike.
In particular,
its close relationship to Java(TM) makes
We'll use the label just
created
the following
exercises
and examples.
the two languages, when used in combination, ideal for Web and distributed enterprise
Working with application
Tooltipsdevelopment.
This tutorial begins with coverage of some of the basics of Python programming. Using
The first JLabel we'll look at is toolTip, which provides help text about what a component does.
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to
develop
understanding of concepts and practical
>>> label.toolTipText
= programming
"Tooltips
are ancool"
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities
that Python
with Java
APIs
for professional
If you go to the frame
and hover and
the shows
mouse the
overways
the JLabel
forinterfaces
a few seconds,
a little
window
pops up with
application
the message "Tooltips
are cool."development.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web

Color and the and


Opaque
Property
Enterprise
Applications with Jython covers important topics such as:

The opaque property allows a component to set its own background color rather than use the color of the
container's background (theFundamental
default). programming concepts, including statements, expressions,
interpreters, and compilers

>>> label.opaque
Python basics, including operators, string formatting, namespaces, classes, errors,
0
and exceptions
The0 (false) value tells us that the default is set, so the code above will change if we change the background.
Object-oriented programming concepts

>>> frame.contentPane.background = (255,0,0)


File input/output
However, just changing the label background won't do anything. When we execute the following code setting
intrinsic
the panel to green, the labelPython's
stays the
same: functions
Formatting,
parsing,
and manipulating
strings
>>> label.background
= (0,
255,
0)
with the
Java APIs
working
with we'll
Java get
Streams
Instead, we have to set the Interfacing
opaque property
to true
( 1). and
Once
we do that,
the right label color when
the label background changes.
Using Python and Java Swing to create GUIs

>>> label.opaque = 1

Working with SQL and JDBC(TM)


You can also set the foreground of a component.
Python and Java applets

>>> label.foreground = (255,255,255)

In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

An Easier Way to Work with Colors

Publisher:the
Addison
Wesleyfor your common colors. The java.awt.Color class
You don't have to remember
RGB values
Date:
Junesimple
28, 2002
makes working withPub
colors
pretty
by defining the following constants:
ISBN: 0-201-61616-5

Table of
Color.black

Pages: 640
Contents
Color.blue
Color.cyanCharacterized by ease of use, richness of expression, and concise syntax, Python has
Color.darkGray
remained a premier programming language for more than a decade, and is used by
Color.graynovices and professionals alike. In particular, its close relationship to Java(TM) makes
Color.green
the two languages, when used in combination, ideal for Web and distributed enterprise
Color.lightGray
application development.
Color.magenta
Color.orange
This tutorial begins with coverage of some of the basics of Python programming. Using
Color.pinkplenty of skill-building exercises and interactive programming sessions, this book will
Color.red help those new to programming develop an understanding of concepts and practical
Color.white
techniques. For experienced programmers, the book demonstrates Python's breadth of
Color.yellow
capabilities and shows the ways that Python interfaces with Java APIs for professional

application development.
Try this short exercise:
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
>>> from java.awt
import
Color
#import
thetopics
color
class
and Enterprise
Applications
with Jython covers
important
such as:

>>> label.background = Color.black


>>> label.foreground = Color.white

#set the background black


#set the foreground white

Fundamental programming concepts, including statements, expressions,


Now take a look at the interpreters,
frame that contains
your label.
and compilers

>>> label.foreground
= including
Color.black
thenamespaces,
foreground
Python basics,
operators, string #set
formatting,
classes,black
errors,
>>> label.background
= Color.white
#set the background white
and exceptions
Object-oriented
programming concepts
Unlike javax.swing.JLabel
,java.awt.Label
is pretty much always opaque and so has no opaque
property. However, the foreground and background properties work the same for both.
File input/output

Fonts

Python's intrinsic functions

strings
JComponent has a fontFormatting,
property thatparsing,
allows and
you manipulating
to see what font
the label is using. It works essentially the
same in both java.awt.Label and javax.swing.JLabel.
Interfacing with the Java APIs and working with Java Streams

>>> label.font
Using Python and Java Swing to create GUIs
javax.swing.plaf.FontUIResource[family=dialog.bold,name=Dialog,style=bold,
size=12]
Working with SQL and JDBC(TM)
label.font also allows
you toand
setJava
the label
font.
Python
applets
>>> font = Font("Times
Newcontains
Roman",
Font.BOLD,
12)and installing the Python
In addition, the book
instructions
for downloading
>>> label.font
=
font
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

Finding Fonts

Publisher: Addison Wesley


ImportGraphicsEnvironment
.
Pub Date: June 28, 2002

>>> from java.awt


import GraphicsEnvironment
ISBN: 0-201-61616-5
Table
>>> ofge = GraphicsEnvironment.getLocalGraphicsEnvironment()
Pages: 640
Contents

Invokelen().
Characterized by ease of use, richness of expression, and concise syntax, Python has
remained= a ge.getAllFonts()
premier programming language for more than a decade, and is used by
>>> fontlist
novices
and
professionals alike. In particular, its close relationship to Java(TM) makes
>>> len(fontlist)
the
two
languages,
when used in combination, ideal for Web and distributed enterprise
98
application
development.
>>> for x in range (0, 10):

...
...

print
fontlist[x].name
This tutorial begins with coverage of some of the basics of Python programming. Using

plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
Print the output.
techniques. For experienced programmers, the book demonstrates Python's breadth of
and shows
the ways that Python interfaces with Java APIs for professional
Abadi MT capabilities
Condensed
Light
application development.
Arial

Arial
Arial
Arial
Arial
Arial
Arial
Arial
Arial

Black
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
Cursiva
and Enterprise Applications with Jython covers important topics such as:
Narrow
Narrow fed
NarrowFundamental
fed kursiv
programming concepts, including statements, expressions,
Narrowinterpreters,
kursiv and compilers
Negreta
Negreta
cursiva
Python
basics, including operators, string formatting, namespaces, classes, errors,

and exceptions
To save space only the first ten fonts appear. To deal with large font lists we can start with the font
families, which group
fonts that haveprogramming
similar characteristics.
Object-oriented
concepts

>>> familiesFile
= input/output
ge.getAvailableFontFamilyNames()
>>> len(families)
Python's intrinsic functions
62
parsing,
and manipulating strings
>>> for x inFormatting,
range (0,
10):
...
print families[x]
Interfacing with the Java APIs and working with Java Streams
...
Abadi MT Condensed
Light
Using Python
and Java Swing to create GUIs
Arial
Arial Black Working with SQL and JDBC(TM)
Arial Narrow
Book AntiquaPython and Java applets
Bookman Old Style
In addition, the book contains instructions for downloading and installing the Python
Calisto MT
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
Century Gothic
and numerous
code samples make this book a useful learning experience.
Comic Sans
MS
Copperplate Gothic Bold

Whether you are a sophisticated computer user new to programming or a serious


application developer, Python Programming with the Java(TM) Class Libraries will
To find out more about fonts, look up java.awt.Font; then try to create an italicized font.
give you insight into the power of Python and the know-how to put it to work.

Icons

777

JLabel has an icon property that you can use to set an image in the label component.

Python
Programming
ImportImageIcon
from javax.swing.

>>> from

with the Java Class Libraries: A Tutorial for Building


Web and Enterprise Applications with Jython
By Richard Hightower
javax.swing
import ImageIcon

Create the image icon, and


assign Addison
it to the icon
property. (In this example, I used one of the images that ships
Publisher:
Wesley
with the JDK. You mayPub
haveDate:
to adjust
the
file
path
if you installed the JDK somewhere else or if you're using a
June 28, 2002
different JDK version.)
ISBN: 0-201-61616-5

Table of

Pages: 640

>>> Contents
label.icon = ImageIcon("c:\\jdk1.2.1\\demo\\jfc\\java2d\\images\\duke.gif
>>> frame.pack()
Characterized by ease of use, richness of expression, and concise syntax, Python has
remainedconstructor
a premier programming
language
a decade,
anduse
is used
byor jpeg
Note that the ImageIcon
we're using takes
a file for
pathmore
to anthan
image.
You can
any gif
novices
and
professionals
alike.
In
particular,
its
close
relationship
to
Java(TM)
makes
image. You also can change the position of the text relative to the icon.
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
>>> label.horizontalTextPosition
= JLabel.RIGHT

>>> label.verticalTextPosition = JLabel.TOP

This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises
and interactive programming sessions, this
will in
Look up setVerticalTextPosition
and setHorizontalTextPosition
forbook
JLabel
help
those
new
to
programming
develop
an
understanding
of
concepts
and
practical
the Java API documentation; then move the label text to the bottom, to the right of the Duke icon.
techniques. For experienced programmers, the book demonstrates Python's breadth of
Images make graphical
user interfaces
graphical.
JLabel
can easily
display
images
as icons,
but for
capabilities
and shows
the ways
that Python
interfaces
with
Java APIs
for professional
java.awt.Label
image display
is not so simple.
application
development.

Mnemonics

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

Mnemonics allow users to select a component for input with the keyboard and can be displayed with labels.
However, since labels can'tFundamental
do anything programming
other than display
text and
images,statements,
they need the
help of another
concepts,
including
expressions,
component to receive the input,
such asand
a container
or text field. Here's how to set a mnemonic:
interpreters,
compilers

>>> label.setDisplayedMnemonic('J')
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
The first J is underlined, which signifies it as the mnemonic. JLabel'slabelFor property allows you to set
the component that will receive
the input focus
when the concepts
mnemonic is pressed. On Windows, you activate the
Object-oriented
programming
mnemonic by pressing Alt-J; on most UNIX boxes, you press meta-J.
File input/output
UsinglabelFor , let's set up a few components and associate one of them with the label's mnemonic. Add
Python's
functions
two buttons to the frame, and
set theintrinsic
layout so
that the frame displays all of the components, that is, the two
buttons and the label.
Formatting, parsing, and manipulating strings

>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>

from javax.swing import JButton


#import the JButton class
Interfacing
with the Java APIs and working
with Java
Streams
j = JButton ("J
button")
#create
two
buttons
b2 = JButton ("button 2")
Using Python and Java Swing to create GUIs
frame.contentPane.add(j)
#add the buttons to the frame
frame.contentPane.add(b2)
Working with SQL and JDBC(TM)
from java.awt import FlowLayout
#import the FlowLayout class
frame.contentPane.layout
= FlowLayout() #set the layout
Python and Java applets
frame.pack()
#layout the components

In addition, the book contains instructions for downloading and installing the Python
Associate the label with
the j and
button.
language
the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.

>>> label.labelFor = j

Whether you are a sophisticated computer user new to programming or a serious


When you press Alt-J,
the j button
will receive
theProgramming
input focus. You
becauseClass
its text
becomeswill
outlined
application
developer,
Python
withcan
the tell
Java(TM)
Libraries
in light gray. Now use
the
Tab
key
to
put
the
focus
on
the
b2
button
(the
one
with
"
button
2
").
Most
often,
give you insight into the power of Python and the know-how to put it to work.
labelFor is assigned a text field or some other component that is incapable of displaying a mnemonic.

JButton

777

We touched on buttons
in Chapter
11. They're
pretty
we'llLibraries:
cover themAhere.
Import
JFrame,
Python
Programming
with
thesimple,
JavasoClass
Tutorial
forthe
Building
JButton,Frame,Web
and Button
classes.Applications with Jython
and Enterprise
By Richard Hightower

>>>
>>>
>>>
>>>
>>>
>>>

from javax.swing import JFrame, JButton


button = JButton("J
Button")
Publisher: Addison Wesley
frame = JFrame(visible=1)
Pub Date: June 28, 2002
frame.title = "JFC"
ISBN: 0-201-61616-5
frame.contentPane.add(button)
Table
of
Pages: 640
Contents
frame.pack()
Characterized by ease of use, richness of expression, and concise syntax, Python has

Java Event Handling


JButton
remained aand
premier
programming language for more than a decade, and is used by

novices and professionals alike. In particular, its close relationship to Java(TM) makes
To demonstrate Javathe
event
we'll
create
a class
that implements
using
twohandling
languages,
when
used
in combination,
ideal ActionListener
for Web and distributed. Then,
enterprise
addActionListener
, we'll
register an instance of the Listener class to the button.
application
development.
Define the Listener
This class.
tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
>>> from java.awt.event
import ActionListener
help those new to programming
develop an understanding of concepts and practical
>>> class ButtonListener(ActionListener):
techniques. For experienced programmers, the book demonstrates Python's breadth of
...
def actionPerformed(self,
capabilities and shows the ways thate):
Python interfaces with Java APIs for professional
...
print
e.getSource().getText()
+ " was clicked"
application development.

...
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
Create an instance ofand
Listener
and register itwith
withJython
the button.
Enterprise, Applications
covers important topics such as:

>>> listen = ButtonListener()


>>> button.addActionListener(listen)
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
Click the J button a few times to see the following message in the DOS box:
Python basics, including operators, string formatting, namespaces, classes, errors,
J button was clicked
and exceptions

J button was clicked


J button was clicked
Object-oriented programming concepts
File input/output
Python Event Handling
and JButton
Python's intrinsic functions
Again, since we covered Java event handling in Chapter 11, we'll just quickly review it here, continuing with the
Java example. Define the event
handler,parsing,
which and
is just
a function with
an argument.
Formatting,
manipulating
strings

>>> def actionPerformed(e):


Interfacing with the Java APIs and working with Java Streams
>>>
print "The Python event handler"
Using Python and Java Swing to create GUIs
>>>
source = e.source
>>>
if source.class is JButton:
Working
with SQL and JDBC(TM)
>>>
print
source.text
+ " was clicked"
Python
and Java
applets
Assign the handler by setting
the button's
actionPerformed
event property to the actionPerformed
event.
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development
Kit (JDK). Terminology, definitions, explanations,
>>> button.actionPerformed
= actionPerformed
and
numerous
code
samples
make
this
book a useful learning experience.
>>> def actionPerformed(e):

>>>
print "The Python event handler"
you are a sophisticated computer user new to programming or a serious
>>>
source Whether
= e.source
application
developer,
Python Programming with the Java(TM) Class Libraries will
>>>
if source.class
is JButton:
give
you
insight
into
the
power+of "
Python
the know-how to put it to work.
>>>
print source.text
wasand
clicked"
>>> button.actionPerformed = actionPerformed

777

Try the event handler by pressing the button with the mouse pointer. If you haven't been following alongas you
should have beenread and run buttons.py in Chapter 12.

Python Programming with the Java Class Libraries: A Tutorial for Building

Button and JButton


Web andShared
EnterpriseProperties
Applications with Jython
By Richard Hightower

Using the enabled(Boolean b) property, disable the AWT and JFC buttons.
Publisher: Addison Wesley

>>> button.enabled
= June
0 28, 2002
Pub Date:
ISBN: 0-201-61616-5

Table
You'll
noticeofthat the buttons' text is grayed out. If you click on them, you won't get any action event. To enable

Pages: 640
Contents
the buttons
again use:

Characterized
>>> button.enabled
= 1by ease of use, richness of expression, and concise syntax, Python has

remained a premier programming language for more than a decade, and is used by
novices
anddoprofessionals
alike. In particular, its close
relationship
to Java(TM) makes
There are some things
you can
with java.swing.JButton
that you
can't do with
the
two
languages,
when
used
in
combination,
ideal
for
Web
and
distributed
enterprise
java.awt.Button. For one, with the mnemonic (char mnemonic) property you can set
the button so
application
development.
that it receives input focus when you press a shortcut key.
This tutorial
with one
coverage
of some
the basics
Python
programming.
Using
You can set up the frame
to showbegins
more than
component
andofthen
add anof
extra
component
to it. Import
plenty
of
skill-building
exercises
and
interactive
programming
sessions,
this
book
will
FlowLayout (we'll get into layout managers in Chapter 14).
help those new to programming develop an understanding of concepts and practical
>>> from java.awt
import
FlowLayout
techniques.
For experienced
programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
Add a second buttonapplication
to each of the
frames.
development.

>>> frame.contentPane.add(JButton("second
button"))
Python Programming with the Java(TM) Class Libraries:
A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
Set the layout to FlowLayout so that the extra components are visible.

>>> frame.contentPane.layout
= FlowLayout
Fundamental programming
concepts, including statements, expressions,
interpreters, and compilers
Pack the frames so that the layout takes effect.
Python basics, including operators, string formatting, namespaces, classes, errors,
>>> frame.pack() and exceptions
To see how the mnemonic Object-oriented
property works, programming
set it with JButton
concepts.

>>> button.setMnemonic('J')
File input/output
>>> button.mnemonic = ord('J')

#Does the same as above

Python's intrinsic functions


Go to the JFC frame, and use the Tab key to select the second button. Now type in Alt-J (meta-J on UNIX or
apple-J on Mac). The resultFormatting,
is that JButton
input focus.
parsing,will
andhave
manipulating
strings
Want to try this with java.awt.Button
You APIs
can't.and
Mnemonics
JFC-only
feature. Another JFC
Interfacing with the?Java
working are
witha Java
Streams
exclusive is associating an image icon with a button. The icon property works just like its Jlabel counterpart.
Using Python and Java Swing to create GUIs

icon (Icon defaultIcon)


Working with SQL and JDBC(TM)
Here's how you set an image in a button:
Python and Java applets

>>> from javax.swing import ImageIcon


>>> button.icon
= ImageIcon("c:\\jdk1.2.1\\demo\\jfc\\java2d\\images\\duke.gi
In addition,
the book contains instructions for downloading and installing the Python
>>> frame.pack()
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
You can also move the button's text in relation to its icon. Again, this works just like it does in JLabel, as we
Whether you are a sophisticated computer user new to programming or a serious
saw in an earlier example.
application developer, Python Programming with the Java(TM) Class Libraries will
As an exercise, lookgive
up the
forthe
the power
JButton
class;and
then
a button
youproperties
insight into
of Python
thecreate
know-how
to whose
put it toimage
work.changes when
the mouse rolls over it. Hint: Check out javax.swing.AbstractButton, the superclass of
JButton, particularly its setRolloverEnabled() and setRolloverIcon() methods.
AbstractButton contains much of the functionality for JButton. It's also a base class for
JCheckBox,JRadioButton,JMenuItem, and JToggleButton, which means that all of those

777

classes can be used interchangeably


(that is, polymorphically).
ManyLibraries:
of the methods
and properties
we use with
Python Programming
with the Java Class
A Tutorial
for Building
JButton we can also
with
any of AbstractButton
's subclasses.
Webuse
and
Enterprise
Applications with Jython
By Richard Hightower

JTextField

Publisher: Addison Wesley


Pub Date: June 28, 2002

JTextField allows you to edit text in text fields. It's pretty basic and can be explained with a simple
ISBN: 0-201-61616-5
example.
Import
JTextField
and JFrame from the javax.swing package.
Table
of

Contents

Pages: 640

>>> from javax.swing import JTextField


Characterized by ease of use, richness of expression, and concise syntax, Python has
premier
and ishow
usedtobyset and
Create a frame and aremained
text field,a and
add itprogramming
to the frame.language
We'll usefor
thismore
text than
field atodecade,
demonstrate
novices
and
professionals
alike.
In
particular,
its
close
relationship
to
Java(TM)
makes
read text. Create the frame.
the two languages, when used in combination, ideal for Web and distributed enterprise
>>> frame = JFrame()
application development.
Create the TextField
instance.
This tutorial
begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
>>> textFieldhelp
= those
JTextField(20)
new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
Add the instance to the center of the frame.
capabilities and shows the ways that Python interfaces with Java APIs for professional
application
development.
>>> from java.awt
import
BorderLayout

>>> frame.add(textField, BorderLayout.CENTER)

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

Default Layout Manager


Fundamental programming concepts, including statements, expressions,
interpreters,
andframe
compilers
The default layout manager
for the
is BorderLayout, which essentially allows you to
add components to a frame's north, south, east, and west borders and its center region. We'll cover
Python
basics,
operators, string formatting, namespaces, classes, errors,
it and the other layout
managers
in including
Chapter 14.
and exceptions
Now we'll create a toolbar,Object-oriented
using a panel and
two buttons,concepts
that will allow us to work with the text field's
programming
properties. Import Panel, and create a panel for a toolbar.
File input/output

>>> from java.awt import Panel


>>> toolbar = Panel()
Python's intrinsic functions

Create two buttons for setting


and reading
text field
text.
Formatting,
parsing,
and manipulating
strings

>>> readText = JButton("Read


Text")
Interfacing with the Java
APIs and working with Java Streams
>>> setText = JButton("Set Text")
Using Python and Java Swing to create GUIs
Add the buttons to the toolbar.
Working with SQL and JDBC(TM)

>>> toolbar.add(readText)
Python and Java applets
>>> toolbar.add(setText)
In north
addition,
the of
book
Add the buttons to the
border
the contains
frame. instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
>>> frame.add(toolbar,
BorderLayout.NORTH)
and numerous code
samples make this book a useful learning experience.
Pack the frame to make
the component
layout visible.computer user new to programming or a serious
Whether
you are a sophisticated
application developer, Python Programming with the Java(TM) Class Libraries will
>>> frame.pack()
give you insight into the power of Python and the know-how to put it to work.

>>> frame.visible = 1

777

Set up the button event handlers to manipulate the text field. This one reads the text and prints it out to the
console window:

>>> def readTextClicked(e):


Python Programming with the Java Class Libraries: A Tutorial for Building
...
printWeb
textField.text
and Enterprise Applications with Jython
...
By Richard Hightower
This one sets the text field
text: Addison Wesley
Publisher:
Pub Date: June 28, 2002
>>> def setTextClicked(e):
ISBN: 0-201-61616-5
... Table oftextField.text
= "I really like Java and Python"

Pages:
640
... Contents

Characterized
by ease of use, richness
of expression,
andthem
concise
syntax,
Python has
Associate the handlers
with the actionPerformed
event
by assigning
to the
button's
remained
a
premier
programming
language
for
more
than
a
decade,
and
is
used by
actionPerformed property.
novices and professionals alike. In particular, its close relationship to Java(TM) makes
>>> readText.actionPerformed
= in
readTextClicked
the two languages, when used
combination, ideal for Web and distributed enterprise
>>> setText.actionPerformed
application development. = setTextClicked
tutorial
begins
with
of button
some of
the basics
Enter in some text inThis
the text
field,
and hit
thecoverage
Read Text
a few
times of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
Hello how arehelp
you
those new to programming develop an understanding of concepts and practical
Hello how aretechniques.
you
For experienced programmers, the book demonstrates Python's breadth of
Hello how arecapabilities
you
and shows the ways that Python interfaces with Java APIs for professional
application development.
Hit the Set Text, and then the Read Text button.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
I really likeandJava
andApplications
Python with Jython covers important topics such as:
Enterprise

I really like Java and Python


I really like Java and Python

Fundamental programming concepts, including statements, expressions,


Work with the buttons andinterpreters,
the text fieldand
to verify
that the field is working like java.awt .TextField.
compilers
Most of the functionality for
JTextField
is in JTextComponent
. This is
an abstract classes,
class anderrors,
the
Python
basics, including
operators, string formatting,
namespaces,
superclass of JTextField
JTextArea (the latter represents a multi line text field). JEditorPane
and and
exceptions
andJTextPane are subclasses of JTextComponent; they add the ability to view HTML and RTF (Rich
Object-oriented
programming
concepts
Text Format) text and to display
in-text components
and icons.
As an exercise, look up JTextField
and JTextComponent in the Java API documentation. Try
File input/output
creating an application that uses JEditorPane to view an HTML page.
Python's intrinsic functions

JCheckBox

Formatting, parsing, and manipulating strings

Interfacing
with the Java
and working
with
Java Streams
Checkboxes represent a true
or false condition.
Let'sAPIs
illustrate
them with
an example
application for choosing
pizza toppings (jfc_checkbox.py). Import java.awt .Checkbox , and create checkboxes that represent pizza
Using Python and Java Swing to create GUIs
toppings.

>>>
>>>
>>>
>>>
>>>
>>>
>>>

Workingimport
with SQLJCheckBox
and JDBC(TM)
from javax.swing
pepperoni = JCheckBox("pepperoni")
Python and Java applets
peppers = JCheckBox("peppers")
olives = InJCheckBox("olives")
addition, the book contains instructions for downloading and installing the Python
anchovieslanguage
= JCheckBox("anchovies")
and the Java Development Kit (JDK). Terminology, definitions, explanations,
onions = and
JCheckBox
("onions")
numerous code
samples make this book a useful learning experience.
sausage = JCheckBox ("sausage")

Whether you are a sophisticated computer user new to programming or a serious


Create a frame to putapplication
the checkboxes
in. Python Programming with the Java(TM) Class Libraries will
developer,
give you insight into the power of Python and the know-how to put it to work.

>>> from java.swing import JFrame


>>> frame = JFrame(title="Pick your topping", visible = 1)

777

Add the checkboxes to the frame.

>>>
>>>
>>>
>>>
>>>
>>>

frame.contentPane.add(pepperoni)
Python Programming with the Java Class Libraries: A Tutorial for Building
frame.contentPane.add(peppers)
Web and Enterprise Applications with Jython
frame.contentPane.add(olives)
By Richard Hightower
frame.contentPane.add(anchovies)
frame.contentPane.add(onions)
Publisher: Addison Wesley
frame.contentPane.add(sausage)
Pub Date: June 28, 2002
ISBN: 0-201-61616-5

Table of as the default.


Set pepperoni
Contents

Pages: 640

>>> pepperoni.selected = 1

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained
a premier
programming
language for .more
is the
usedcheckboxes
by
Remember that the default
layout
for a frame
is BorderLayout
If wethan
wanta decade,
to show and
all of
novices
and
professionals
alike.
In
particular,
its
close
relationship
to
Java(TM)
makes
created, we need to reset the layout manager to FlowLayout.
the two languages, when used in combination, ideal for Web and distributed enterprise
>>> from java.awt
import
FlowLayout
application
development.

>>> frame.contentPane.layout = FlowLayout()


This tutorial begins with coverage of some of the basics of Python programming. Using
>>> frame.pack()
plenty of skill-building exercises and interactive programming sessions, this book will
programming
an understanding
of concepts and practical
Set the event handlerhelp
for those
closingnew
thetoframe
to inspectdevelop
the checkboxes'
state.
techniques. For experienced programmers, the book demonstrates Python's breadth of
>>> def frameClosing(event):
capabilities and shows the ways that Python interfaces with Java APIs for professional
...
for checkbox
in frame.components:
application development.

...
if(checkbox.selected == 1): print checkbox.label
...
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
>>> frame.windowClosing
= frameClosing
and Enterprise Applications
with Jython covers important topics such as:
Work with the checkboxes to select toppings; then press the Close button on the frame's top left border (for
Fundamental programming concepts, including statements, expressions,
Windows NT/9X).
interpreters, and compilers

pepperoni
onions
sausage

Python basics, including operators, string formatting, namespaces, classes, errors,


and exceptions
Object-oriented programming concepts

Putting Things Together with JCheck Box

File input/output
Here's the pizza topping application we just wrote. Follow along, and make sure to read the comments.
Python's intrinsic functions

# Import JCheckBox and create checkboxes that represent pizza toppings.


and manipulating strings
from javax.swing Formatting,
import parsing,
JCheckBox
cb = JCheckBox
Interfacing with the Java APIs and working with Java Streams

#cb is the JCheckBox class. Remember classes are first class objects in Pytho
Using Python and Java Swing to create GUIs
pepperoni = cb("pepperoni")
checkboxes=(pepperoni,cb("peppers"),cb("olives"),cb("anchovies"),cb("onions")
Working with SQL and JDBC(TM)
,cb("sausage"))
Python and Java applets

# Import JFrame and create a frame to hold our checkboxes.


from javax.swing
import
JFrame
In addition,
the book
contains instructions for downloading and installing the Python
frame = JFrame(title="Pick
your topping",
visible =definitions,
1)
language and the Java Development
Kit (JDK). Terminology,
explanations,
and numerous code samples make this book a useful learning experience.

# Import JPanel and set the frame's contentPane to a JPanel.


Whetherimport
you are a sophisticated
from javax.swing
JPanel computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
panel = JPanel()
give you insight
into the power of Python and the know-how to put it to work.
frame.contentPane
= panel
# Now add the checkboxes to the Panel
for a_checkbox in checkboxes:
panel.add(a_checkbox)

777

Python Programming with the Java Class Libraries: A Tutorial for Building

# Set the
pepperoni's state to selected.
Web and Enterprise Applications with Jython
pepperoni.selected
= 1
By Richard Hightower

# Pack the frame


Publisher: Addison Wesley
frame.pack()
Pub Date: June 28, 2002
def frameClosing(event):
forof checkboxISBN:
in 0-201-61616-5
checkboxes:
Table

Pages:
640
Contents if(checkbox.selected == 1): print checkbox.text
Characterized
ease of use, richness of expression, and concise syntax, Python has
frame.windowClosing
= byframeClosing

remained a premier programming language for more than a decade, and is used by
novices
and professionals
alike. means
In particular,
close
relationship
to Java(TM)
makes
Now we want to offer
a one-topping
special, which
that weits
have
to change
the program
so that
the
the
two
languages,
when
used
in
combination,
ideal
for
Web
and
distributed
enterprise
customer can select only one checkbox. (The changes are highlighted in bold.) Add each checkbox to a button
application development.
group.
tutorial begins
withone
coverage
of some of the basics of Python programming. Using
frame.title =This
"Choose
your
Topping"
plenty of skill-building exercises and interactive programming sessions, this book will
new to programming develop an understanding of concepts and practical
#Import help
thethose
ButtonGroup
techniques.
For experienced
programmers, the book demonstrates Python's breadth of
from javax.swing import
ButtonGroup
capabilities
and
shows
the
ways
that Python interfaces with Java APIs for professional
group = ButtonGroup()
application development.

#Add each check box to the group.


Python
with the Java(TM) Class Libraries: A Tutorial for Building Web
for a_checkbox
inProgramming
checkboxes:
and
Enterprise
Applications
with Jython covers important topics such as:
group.add(a_checkbox)
# Now let's Fundamental
assume that
most concepts,
peopleincluding
want statements,
pepperoni.
programming
expressions,
pepperoni.selected
=
1
interpreters, and compilers
It doesn't work, does it? Read
on. basics, including operators, string formatting, namespaces, classes, errors,
Python
and exceptions

JRadioButton

Object-oriented programming concepts

With JFC, to make the buttons


look and behave like radio buttons, you have to use JRadioButton. Let's
File input/output
continue our one-topping example, using JRadioButton in a button group to allow only one checkbox to be
Python's intrinsic functions
selected.

for a_checkbox inFormatting,


checkboxes:
parsing, and manipulating strings
panel.remove(a_checkbox)
Interfacing with the Java APIs and working with Java Streams

group = ButtonGroup()

Using Python and Java Swing to create GUIs

from javax.swing import JRadioButton


Working with SQL and JDBC(TM)
rb = JRadioButton
#rb is JRadioButton class.
#Remember classes
first class objects in Python.
Python andare
Java applets
pepperoni = rb("pepperoni")
In addition, the book contains instructions for downloading and installing the Python

radiobuttons=(pepperoni,rb("peppers"),rb("olives"),rb("anchovies"),
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
rb("onions"),rb("sausage"))
and
numerous code samples make this book a useful learning experience.
Whether you
a sophisticated computer user new to programming or a serious
for a_radiobutton
in are
radiobuttons:
application developer, Python Programming with the Java(TM) Class Libraries will
group.add(a_radiobutton)
give you insight into the power of Python and the know-how to put it to work.
panel.add(a_radiobutton)

pepperoni.selected = 1
frame.pack()

777

Try these exercises: Python Programming

with the Java Class Libraries: A Tutorial for Building


Web and Enterprise Applications with Jython
By Richard Hightower

Change the event handler to work with JRadioButton, and then look up AbstractButton, the
superclass of JButton,JCheckBox, and JRadioButton. You might also try adding picture
Publisher: Addison Wesley
icons to represent the different toppings.
Pub Date: June 28, 2002

ISBN: 0-201-61616-5
With the
Table
of technique we used to replace checkboxes with radio buttons, replace radio buttons with toggle
Pages:
640
buttons (javax.swing.JToggleButton
). Can you think of ways to switch between all three?
Contents

Hint:JToggleButton has the same properties that JCheckBox and JRadioButton have.
Characterized
by ease
of of
use,
of expression,
and concise syntax,, Python
Remember that
JButton gets
much
itsrichness
functionality
from AbstractButton
so all ofhas
its
remained
a
premier
programming
language
for
more
than
a
decade,
and
is
used to
byadd icons
propertiesicon, text, mnemonics, and so forthwork for these classes as well. If you want
or change text,novices
you doand
it inprofessionals
the same way.alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.

List and JList

This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of
skill-building
and interactivemode
programming
this book will
List components represent
choices.
They canexercises
be in single-selection
(one item)sessions,
or multi-selection
mode
help
those
new
to
programming
develop
an
understanding
of
concepts
and
practical
(more than one item). Let's create an example list in the interactive interpreter.
techniques. For experienced programmers, the book demonstrates Python's breadth of
>>> from javax.swing
import
capabilities and
shows theJList
ways that Python interfaces with Java APIs for professional
>>> list_items
=
["Bruce",
"Darrell",
"Tony", "Debbie", "Karen"]
application development.

>>> list = JList(list_items)


Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
Here's the interactiveand
session
to create
a frame: with Jython covers important topics such as:
Enterprise
Applications

>>>
>>>
>>>
>>>
>>>

from javax.swing import JFrame


Fundamental programming
concepts, including statements, expressions,
frame = JFrame("JList
example")
interpreters, and compilers
frame.contentPane.add(list)
frame.pack()
Python basics, including operators, string formatting, namespaces, classes, errors,
frame.visible=1
and exceptions

List Events

Object-oriented programming concepts

Now we want to do something


with our listthat is, handle the list eventsso we need to inspect JList's
File input/output
event properties (or look them up in the Java API documentation).
Python's intrinsic functions
Here's the interactive session to inspect the list properties, with the output formatted to make it a little more
Formatting, parsing, and manipulating strings
readable.

Interfacing with the Java APIs and working with Java Streams
>>> getEventsInfo(JList)
[<beanEventProperty valueChanged for event interface javax.swing.event.ListSe
Using Python and Java Swing to create GUIs
We can inspect the events more closely using getEventsInfo to print and pause.
Working with SQL and JDBC(TM)

>>> getEventsInfo(JList, 1, 1)
applets
Event Property: Python and Java
valueChanged
Defined in:
javax.swing.event.ListSelectionListener
In addition, the book contains instructions for downloading and installing the Python
Event:
javax.swing.event.ListSelectionEvent

language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.

Event properties for javax.swing.event.ListSelectionEvent:


lastIndex
Type: org.python.core.PyBeanProperty
Whether you are a sophisticated
computer user new to programming or a serious
valueIsAdjusting
Type:
application developer,
Pythonorg.python.core.PyBeanProperty
Programming with the Java(TM) Class Libraries will
firstIndex
org.python.core.PyBeanProperty
give you insight intoType:
the power
of Python and the know-how to put it to work.
If you look up the list properties in the Java API documentation, these are the ones you'll find:

777

LastIndex last row that may have changed

Python Programming
with
the Java
Class
Libraries: A Tutorial for Building
ValueIsAdjusting
true if this
is multiple
change
events
Web and Enterprise Applications with Jython
By
Richard
Hightower
FirstIndex
first row
that may have changed

ListSelectionEvent
allows
handling
of an item selection event, either the Java way or the Python way.
Publisher:
Addison
Wesley
Here's the Python way:

Pub Date: June 28, 2002


ISBN: 0-201-61616-5

>>> Table
def ofeventListener(event):
Pages: 640
... Contents
list = event.source # get a reference to the list,
...
# theofevent's
source
Characterized by ease of use, richness
expression, and
concise syntax, Python has
...
indexremained
= event.firstIndex
a premier programming language for more than a decade, and is used by
...
printnovices
list.model.getElementAt(index)
and professionals alike. In particular, its close relationship to Java(TM) makes
...
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
Now try selecting some list items.
This tutorial begins with coverage of some of the basics of Python programming. Using
I'm going to leave the Java way as an exercise. I'll give you two hints to help you, but don't read them unless you
plenty of skill-building exercises and interactive programming sessions, this book will
get stuck. Hint1: Create a class that subclasses java.awt .event.ItemListener; then create an
help those new to programming develop an understanding of concepts and practical
instance of that class, and pass it to the list.addItemListener() method. Hint2: The subclass should
techniques. For experienced programmers, the book demonstrates Python's breadth of
override the itemStateChanged() method with the arguments self and event.
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.

JComboBox

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise
Applications
with
covers
important
topics
such
JComboBox is a combination
dropdown
list and
textJython
field that
comes
in handy
when
youas:
have limited real
estate on a panel. It's something of a cross between java.swing.JList and
javax.swing.JTextField. In fact, JComboBox looks a lot like javax.swing.JList, its only
Fundamental programming concepts, including statements, expressions,
real difference being that it uses the addItem() method to add items to the list.
interpreters, and compilers
Here's the JComboBox code:
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
# Import List, create
a list instance and populate the list instance.

from javax.swing import JComboBox


Object-oriented programming concepts
list = JComboBox()
list_items = ("Bruce",
"Darrell", "Tony", "Satesh", "Debbie", "Karen")
File input/output
for item in list_items:
Python's intrinsic functions
list.addItem()()(item)
Formatting, parsing, and manipulating strings

# Create a frame and add the list to the frame.


the Java APIs and working with Java Streams
from javax.swing Interfacing
import with
JFrame
frame = JFrame("Combobox Example")
Using Python and Java
Swing to create GUIs frame.pack()
frame.contentPane.add(list);
frame.visible=1;
Working with SQL and JDBC(TM)

# Handle item event.


from java.awt.event
ItemEvent
Pythonimport
and Java applets
def eventListener(event):
list = event.itemSelectable
In addition, the book contains instructions for downloading and installing the Python
item = event.item
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
print "Current
item
:" + make
`item`
and numerous
code samples
this book a useful learning experience.
if (event.stateChange == ItemEvent.SELECTED):
Whether
are a sophisticated
computer user new to programming or a serious
print
" you
--selected
items--"
developer,
Python Programming with the Java(TM) Class Libraries will
forapplication
item in
list.selectedObjects:
give print
you insight
the`item`
power of Python and the know-how to put it to work.
" into
" +
list.itemStateChanged = eventListener

777

It's a little different from the JList version, but close enough.

As an exercise, try changing


the previous example
to make
theClass
combo
box editable.
Hint: Look
up the
Python Programming
with the
Java
Libraries:
A Tutorial
for Building
JComboBox properties
and methods,
particularly
setEditable
Web and
Enterprise
Applications
with Jython.
By Richard Hightower

Working with JList


Publisher: Addison Wesley
Pub Date:
June
28, 2002 splits the logic for the model, view, and controller into different
The Model View Controller
(MVC)
architecture
0-201-61616-5
class sets. For example, the ISBN:
JList
component constructor takes a reference to ListModel. Here's an
Table of

Pages:
640
example
of JList (JList.py)
that's
similar to our JComboBox example:
Contents

# ImportCharacterized
List, create
list
instance
and
list
by ease ofause,
richness
of expression,
and populate
concise syntax,the
Python
has instance.
from javax.swing
import
remained
a premierJList
programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes

list_items = the
("Bruce",
"Tony",ideal
"Debbie",
two languages,"Darrell",
when used in combination,
for Web and "Karen")
distributed enterprise
application development.

# Create a list with a default model that uses the above list items
This tutorial begins with coverage of some of the basics of Python programming. Using
list = JList(list_items)
plenty of skill-building exercises and interactive programming sessions, this book will
new to
programming
develop
of concepts and practical
# Createhelp
a those
frame
and
add the
listan understanding
to the frame.
techniques.
For
experienced
programmers,
the
book
demonstrates
Python's breadth of
from javax.swing import JFrame
capabilities
and
shows
the
ways
that
Python
interfaces
with
Java
APIs
for professional
frame = JFrame("JList Example")
application development. frame.visible=1; frame.pack()
frame.contentPane.add(list);
Programming
with the Java(TM)
Class Libraries: A Tutorial for Building Web
# ImportPython
this
for selection
constants
and
Enterprise
Applications
with
Jython
covers
from javax.swing import ListSelectionModelimportant topics such as:
list.selectionMode = ListSelectionModel.MULTIPLE_INTERVAL_SELECTION
Fundamental programming concepts, including statements, expressions,

# Handle item
event.
interpreters,
and compilers
from java.awt.event import ItemEvent
def eventListener(event):
Python basics, including operators, string formatting, namespaces, classes, errors,
list = event.source
and exceptions
print "Current item :" + list.selectedValue
if (list.selectionMode
== ListSelectionModel.MULTIPLE_INTERVAL_SELECTION
Object-oriented programming
concepts
print " --selected items--"
File input/output
for item
in list.selectedValues:
print " " + `item`
Python's intrinsic functions

list.valueChanged = eventListener

Formatting, parsing, and manipulating strings

I said that JList was similar to JComboBox, but there are differences (highlighted in bold). First, JList
Interfacing with the Java APIs and working with Java Streams
has no addItem() (or equivalent) method to add items to the list, so we have to pass list_item to the
constructor (we could haveUsing
passedPython
it to the
constructor).
Second, we have to import
andjava.awt
Java Swing.List
to create
GUIs
javax.swing.ListSelectionModel to get access to the constants to set selectionMode.
selectionMode allows
three types
selection:
single (one item), single contiguous range (a set of items
Working
withof
SQL
and JDBC(TM)
next to each other), and multiple interval (multiple items).Third, the Jlist and JComboBox event properties
Python and Java applets
are different.

the book contains instructions for downloading


the Python and
As an exercise, lookIn
upaddition,
javax.swing.ListSelectionModel
in the and
Javainstalling
API documentation,
language
the Java
Kitlook
(JDK).
Terminology,
explanations,
inspect the event properties
ofand
JList
withDevelopment
jinfo. Then
up the
listener anddefinitions,
event classes
associated with
and
numerous
code
samples
make this book a useful learning experience.
them. Change the last
example
to use
Java
event handling.
Whetherexample
you are isa as
sophisticated
The output for our JList
expected. computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
Current item give
:Karen
you insight into the power of Python and the know-how to put it to work.

----selected items---'Karen'
Current item :Tony
----selected items----

777

'Tony' Python Programming with the Java Class Libraries: A Tutorial for Building
'Karen' Web and Enterprise Applications with Jython
Current item By
:Bruce
Richard Hightower
----selected items---'Bruce'
Publisher: Addison Wesley
'Tony'
Pub Date: June 28, 2002
'Karen'
ISBN: 0-201-61616-5

Table of

Pages: 640

Try toContents
map the output to the code.

by ease
of use,
richness of expression,
syntax,
Don't you think it's aCharacterized
little strange not
to have
an addItem()
method? Iand
do. concise
Remember
that Python
JListhas
uses the
remained
a
premier
programming
language
for
more
than
a
decade,
and
is
used
by
MVC architecture, which keeps the data from view by putting it in the model (the M in MVC). The view (the V
novices
and
alike.
particular,
its closeorrelationship
to Java(TM)
makesa
in MVC) is the JList
itself.
If professionals
you pass a vector
(aIn
sequence
in Python)
an array, JList
will create
the
two
languages,
when
used
in
combination,
ideal
for
Web
and
distributed
enterprise
model based on AbstractListModel.
application development.
If you want to create an easy-to-use list similar to java.awt .List (which is much easier than JList), you
tutorial
begins with coverage of some
of the basics of Pythonisprogramming.
Using
can pass JList anThis
instance
of DefaultListModel
.DefaultListModel
mutable, so you
can
plenty
of
skill-building
exercises
and
interactive
programming
sessions,
this
book
will
add items to it that will show up in the list.
help those new to programming develop an understanding of concepts and practical
techniques. For experienced
bookondemonstrates
Python's breadth of
Here's an example (JList_Model
) of creatingprogrammers,
a mutable listthe
based
our java.swing.JComboBox
capabilities
and
shows
the
ways
that
Python
interfaces
with
Java
APIs
for professional
example. I've highlighted the differences in bold and omitted the last part, which doesn't change.
application development.

# Import List, create a list instance and populate the list instance.
Python Programming
with the DefaultListModel
Java(TM) Class Libraries: A Tutorial for Building Web
from javax.swing
import JList,
and Enterprise Applications with Jython covers important topics such as:

list_items = ("Bruce", "Darrell", "Tony", "Satesh", "Debbie", "Karen")


Fundamental programming concepts, including statements, expressions,

# Create a list with an empty default model


interpreters, and compilers
list = JList(DefaultListModel)
model = list.getModel()
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions

for item in list_items:


model.addElement(item)
Object-oriented programming concepts
...
File input/output
...
Python's intrinsic functions

AnFormatting,
Easierparsing,
Wayandwith
DefaultListModel
manipulating strings
Sincemodel is a property
of Jlist
easier
write thewith
above
would
have been
Interfacing
with the, an
Java
APIsway
andtoworking
Java
Streams

list = JList(DefaultListModel())
Using Python and Java Swing to create GUIs
for item in Working
list_items:
with SQL and JDBC(TM)
list.model.addElement(item)
Python and Java applets
I wrote it the way I did to highlight where the model was coming from.
In addition, the book contains instructions for downloading and installing the Python
and the Java
Development
Kit (JDK).
Terminology,
definitions, explanations,
As an exercise try thelanguage
JList_Model
example
again, without
an instance
of DefaultListModel
, and
and
numerous
code
samples
make
this
book
a
useful
learning
experience.
pass it to the JList constructor. What happens? Why? Hint: Look up AbstractDefaultListModel,
and inspect the class hierarchy returned from the getModel() method.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
Advanced MVC
JListinto the power of Python and the know-how to put it to work.
giveand
you insight
The real advantage to using MVC is that you can have multiple views of the same data model. When the data
changes, the model notifies all of the views so that they're updated.

777

Remember our address


book Programming
application? Wewith
can the
create
a list Class
data model
that uses
it, so thatfor
when
an address
Python
Java
Libraries:
A Tutorial
Building
changes in the list we
can and
automatically
display
the change
in all
open views. To create a data model that's
Web
Enterprise
Applications
with
Jython
compatible with JList
, we need
to implement the ListModel interface.
By Richard
Hightower
For brevity, we're goingPublisher:
to create aAddison
very small
subset of the Address and AddressBook classes that
Wesley
highlights the MVC list.Pub Date: June 28, 2002
ISBN: 0-201-61616-5
What Table
we'll do
of is define an address class that implements the toString() method from

Pages:
java.lang.Object
so that it640
can be displayed in the listbox. Next we'll define an AddressBook class
Contents
that contains instances of Address and acts as a data model. It will have to extend ListModel to work
Characterized
by easewe'll
of use,
richness
expression,
and concise
syntax, Python
has
withjavax.swing.JList
. Finally,
populate
an of
address
bookthe
data modelwith
sample
remained
a
premier
programming
language
for
more
than
a
decade,
and
is
used
by
addresses.
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.

MVC in JTree and JTable

This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
The techniques I'm showing you in the MVC example are the same ones you use with JTree and
help those new to programming develop an understanding of concepts and practical
JTable. You
have to master them if you want to use advanced Swing components.
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
MVC, along with the related design patterns (e.g., Observer/Observable), is explained in Design
application development.
Patterns (Gamma et al., 1995). Reading this book will make you appreciate why MVC was picked
for JList,JTable, and JTree.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

JList_AddressModel.py
Fundamental programming concepts, including statements, expressions,
Here's the complete code for
JList_AddressModel.py.
interpreters,
and compilers

from
from
from
from

string import
* basics, including operators, string formatting, namespaces, classes, errors,
Python
javax.swing and
import
JList, ListModel
exceptions
javax.swing.event import ListDataEvent
java.lang import
Object
Object-oriented
programming concepts

input/output
# Define an File
address
class to hold an address
class Address(Object):
Python's intrinsic
functions
def __init__(self,
name,
phone):
self.name = name
Formatting, parsing, and manipulating strings
self.phone = phone
def __str__(self):
Interfacing with the Java APIs and working with Java Streams
return ljust(self.name,35) + ": " + self.phone
def toString(self):
Using Python and Java Swing to create GUIs
return self.__str__()
def __repr__(self):
Working with SQL and JDBC(TM)
return self.__str__()
Python and Java applets

# Define an address book to hold addresses


In addition, the book contains instructions for downloading and installing the Python
class AddressBook(ListModel):
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
def __init__(self):
and numerous code samples make this book a useful learning experience.

# Fill in some initial data


Whether you are a sophisticated computer user new to programming or a serious
self.list_items = [Address("Darrell", "555-1212")]
application developer, Python Programming with the Java(TM) Class Libraries will
self.list_items.append(Address("Bruce", "555-1212"))
give you insight into the power of Python and the know-how to put it to work.
self.list_items.append(Address("Karen", "555-1212"))
self.list_items.append(Address("Tony", "555-1212"))
self.list_items.append(Address("Chris", "555-1212"))

777

self.listeners
= []
# ToClass
hold
listeners
Python Programming
with the Java
Libraries:
A Tutorial for Building
Web and Enterprise Applications with Jython

# public
int getSize()
By Richard Hightower
# Returns the length of the list.
def getSize(self):
Publisher: Addison Wesley
return
len(self.list_items)
Pub Date:
June 28, 2002
#
public
Object getElementAt(int index)
ISBN: 0-201-61616-5
Table of # Returns the value at the specified index.
Pages: 640
Contents
def getElementAt(self, index):
return
self.list_items[index]
Characterized
by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by

# public
addListDataListener(ListDataListener
l)
novices andvoid
professionals
alike. In particular, its close relationship to Java(TM) makes
# Add
a languages,
listener
notified
the
list enterprise
data
the two
whenthat
used ingets
combination,
ideal forwhen
Web and
distributed
# model
gets
changed
application
development.
# Parameters:
# lThis
- tutorial
the ListDataListener
begins with coverage of some of the basics of Python programming. Using
def addListDataListener(self,
plenty of skill-building exercises and listener):
interactive programming sessions, this book will
print
"somebody
is listening:
" + `listener.class`
help those
new to programming
develop an understanding
of concepts and practical
self.listeners.append(listener)
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional

# public
RemoveListDataListener(ListDataListener l)
applicationvoid
development.
# Removes a listener
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
# Parameters:
Applications with Jython covers important topics such as:
# land-Enterprise
the ListDataListener
def RemoveListDataListener(listener):
print "somebody is ignoring: " + `listener.class`
Fundamental programming concepts, including statements, expressions,
self.listeners.remove(listener)
interpreters, and compilers

# AddAddress()
Python basics, including operators, string formatting, namespaces, classes, errors,
# Adds and
anexceptions
address to the address book
def AddAddress (self, name, number):
self.list_items.append(Address(name,
number))
Object-oriented programming concepts
# File
Notify
each listener that our data has changed.
input/output
# Being aware that our data changed, they can
intrinsic
functions
# Python's
update
their
view to reflect the changes
for each_listener in self.listeners:
Formatting,
parsing, and manipulating strings
start
= len(self.list_items)
end = len(self.list_items)
Interfacing with the Java APIs and working with Java Streams
type = ListDataEvent.INTERVAL_ADDED
event
= ListDataEvent(self,
Using Python
and Java Swing to create GUIstype, start, end)
each_listener.intervalAdded(event)
Working with SQL and JDBC(TM)

AddressBook = AddressBook()
Python and Java applets

# Create 2 lists using our address book list model


In addition, the book contains instructions for downloading and installing the Python
list = JList(AddressBook)
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
list2 = JList(AddressBook)
and numerous code samples make this book a useful learning experience.

# Create a frame and add the lists to the frame.


Whetherimport
you are a sophisticated
from javax.swing
JFrame computer user new to programming or a serious
application
developer,
Python Programming with the Java(TM) Class Libraries will
from java.awt import FlowLayout
give
you
insight
into
the
of Python
andExample")
the know-how to put it to work.
frame = JFrame("JList Custompower
Data
Model
frame.contentPane.layout = FlowLayout() #Added to show both lists
frame.contentPane.add(list); frame.contentPane.add(list2)
frame.visible=1; frame.pack()

777

#Import Python
this Programming
for selection
constants
with the
Java Class Libraries: A Tutorial for Building
from javax.swing
import
ListSelectionModel
Web and
Enterprise
Applications with Jython
list.selectionMode
= ListSelectionModel.MULTIPLE_INTERVAL_SELECTION
By Richard Hightower

#Handle item
event.
Publisher:
Addison Wesley
from java.awt.event
import
ItemEvent
Pub Date: June 28, 2002
def eventListener(event):
ISBN: 0-201-61616-5
Table
of = event.source
list

Pages: 640
Contents
print "Current item :" + `list.selectedValue`
if (list.selectionMode
== richness
ListSelectionModel.MULTIPLE_INTERVAL_SELECTION
Characterized by ease of use,
of expression, and concise syntax, Python has
print
"
--selected
items--"
remained a premier programming language for more than a decade, and is used by
fornovices
itemandin
list.selectedValues:
professionals
alike. In particular, its close relationship to Java(TM) makes
print
" " when
+ `item`
the two
languages,
used in combination, ideal for Web and distributed enterprise
application development.

list.valueChanged = eventListener
This tutorial begins with coverage of some of the basics of Python programming. Using

def addNames():
plenty of skill-building exercises and interactive programming sessions, this book will
AddressBook.AddAddress("Geoff",
help those new to programming develop "555-1234")
an understanding of concepts and practical
AddressBook.AddAddress("Bill",
"555-1235")
techniques. For experienced programmers,
the book demonstrates Python's breadth of
AddressBook.AddAddress("Robert",
"555-1257")
capabilities and shows the ways that Python
interfaces with Java APIs for professional
application development.
Run the following in the interactive interpreter:
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
>>> addNames()
and Enterprise Applications with Jython covers important topics such as:

>>> frame.pack()

First, we define the Address


class. programming concepts, including statements, expressions,
Fundamental
interpreters, and compilers

# Define an address class to hold an address


class Address(Object):
Python basics, including operators, string formatting, namespaces, classes, errors,
def __init__(self,
name, phone):
and exceptions
self.name = name
Object-oriented
programming concepts
self.phone
= phone
def __str__(self):
input/output
return File
ljust(self.name,35)
+ ": " + self.phone
def toString()(self):
intrinsic functions
return Python's
self.__str__()
def __repr__(self):
Formatting, parsing, and manipulating strings
return self.__str__()
Interfacing with the Java APIs and working with Java Streams

Address defines three methods: __str__,__repr__ , and toString().__str__creates the string


representation of Address
for Python;
toString()
its Java
equivalent. We need to make Address a
Using
Python and
Java Swing toiscreate
GUIs
string because the listbox uses toString() to display the method. __repr__ displays the string in Python
when the object is referenced
with back
ToJDBC(TM)
override toString(),Address uses
Working
withquotes.
SQL and
java.lang.Object as its base class.
Python and Java applets
Next we define the custom list model, which presents an interesting opportunity to demonstrate events. In
In addition,
thewas
book
contains
instructions
for downloading
installing
the itPython
previous event examples,
our code
geared
to listening
for (handling)
events.and
In this
example,
publishes
language
the source).
Java Development
Kit (JDK).
Terminology,
definitions,
explanations,
events ( AddressBook
is anand
event
To turn things
inside out,
JList will
be registering
a listener
andtonumerous
samples
book
useful learning experience.
withAddressBook
listen for code
events
that tellmake
it thatthis
data
hasachanged.
Whether you
are a sophisticated
computer user
newa to
programming
or aspeak)
serious
AddressBook implements
ListMode
;AddressBook
is thus
subclass
(in Python
of
application developer, Python Programming with the Java(TM) Class Libraries will
ListModel.
give you insight into the power of Python and the know-how to put it to work.

# Define an address book to hold addresses


class AddressBook(ListModel):

777

AddressBook has to override all of ListModel's methods, which are

Python Programming with the Java Class Libraries: A Tutorial for Building

int getSize()
Web and Enterprise Applications with Jython
By Richard Hightower

Object getElementAt(int index)


Publisher: Addison Wesley
void addListDataListener(ListDataListener
l)
Pub Date: June 28, 2002

ISBN: 0-201-61616-5
void RemoveListDataListener(ListDataListener
l)
Table of
Contents

Pages: 640

In the code that follows, be sure to read all of the comments before each AddressBook method, since they
show which ListModel
methodbyisease
being
andofwhat
it does. and concise syntax, Python has
Characterized
ofoverridden
use, richness
expression,
remained a premier programming language for more than a decade, and is used by
# publicnovices
int and
getSize()
professionals alike. In particular, its close relationship to Java(TM) makes
# Returns
thelanguages,
length
ofused
the
list.
the two
when
in combination,
ideal for Web and distributed enterprise
def getSize(self):
application development.

return len(self.list_items)
This tutorial begins with coverage of some of the basics of Python programming. Using

# publicplenty
Object
getElementAt(int
index)
of skill-building
exercises and interactive
programming sessions, this book will
# Returns
value
at the specified
index. of concepts and practical
helpthe
those new
to programming
develop an understanding
def getElementAt(self,
index):programmers, the book demonstrates Python's breadth of
techniques. For experienced
return self.list_items[index]
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.

# public void addListDataListener(ListDataListener l)


Programming
the Java(TM)
Class when
Libraries:
A Tutorial
# Add a Python
listener
thatwith
gets
notified
the
list for Building Web
and
Enterprise
Applications
with
Jython
covers
important
topics
such as:
# data model gets changed
# Parameters:
# l - the ListDataListener
Fundamental programming concepts, including statements, expressions,
def addListDataListener(self, listener):
interpreters, and compilers
print "somebody is listening: " + `listener.class`
self.listeners.append(listener)
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions

# public void RemoveListDataListener(ListDataListener l)


# Removes a Object-oriented
listener programming concepts
# Parameters:
# l - the ListDataListener
File input/output
def removeListDataListener(listener):
Python'sis
intrinsic
functions " + `listener.class`
print "somebody
ignoring:
self.listeners.remove(listener)
Formatting, parsing, and manipulating strings

addListDataListener and removeListDataListener register and unregister listeners for


with the Java
APIs
and remember,
working with
Java
Streams
ListDataEvents fromInterfacing
AddressBook
(which,
you'll
is an
event
source, which means that it
publishes events when they occur). addListDataListener prints out a listener's registration. When you
Using Python and Java Swing to create GUIs
set a model, JList registers listeners to it; when you remove a model, JList unregisters those listeners.
Working with SQL and JDBC(TM)
TheAddressBook class has the AddAddress()method, which adds a new address to list_items
and then notifies each listener
by calling
its applets
intervalAdded() method. AddAddress() first creates a
Python
and Java
ListDataEvent instance to pass to the listener's intervalAdded() method.
In addition, the book contains instructions for downloading and installing the Python
Rest of language
85, 86,
top
AddAddress()
and the
Java87#
Development
Kit (JDK). Terminology, definitions, explanations,
# Adds an
address
to
the
address
book
and numerous code samples make
this book
a useful learning experience.

def AddAddress(self, name, number):


self.list_items.append(Address(name,
number))
Whether you are a sophisticated computer user new
to programming or a serious

application developer, Python Programming with the Java(TM) Class Libraries will

# Notifygive
each
listener
thatof our
changed.
you insight
into the power
Pythondata
and thehas
know-how
to put it to work.
# Being aware that our data changed, they can
# update their view to reflect the changes
for each_listener in self.listeners:
start = len(self.list_items)

777

end = len(self.list_items)
Python Programming with the Java Class Libraries: A Tutorial for Building
type = ListDataEvent.INTERVAL_ADDED
Web and Enterprise Applications with Jython
event = By
ListDataEvent(self,
type, start, end)
Richard Hightower
each_listener.intervalAdded()(event)
Publisher: Addison Wesley

Now we'll create an instance of AddressBook. Then we'll create two JFC lists, passing the instance to them.
Pub Date: June 28, 2002
At this point, the JList instance will call addDataListener to register listeners with the model. You
ISBN: 0-201-61616-5
Tablethis
of with the console output.
can verify
Pages: 640

Contents

AddressBook = AddressBook()
by ease ofour
use, richness
of expression,
and concise
syntax, Python has
#Create Characterized
2 lists using
address
book list
model
remained
a
premier
programming
language
for
more
than
a
decade,
and is used by
list = JList(AddressBook)
novices
and
professionals
alike.
In
particular,
its
close
relationship
to
Java(TM) makes
list2 = JList(AddressBook)

the two languages, when used in combination, ideal for Web and distributed enterprise
development.
The rest of the code application
for this example
is pretty much the same as that for the earlier ones. As a final step, we'll
define a function called addNames() that adds three addresses to the AddressBook list model.
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
def addNames():
help those new to programming develop "555-1234")
an understanding of concepts and practical
AddressBook.AddAddress("Geoff",
techniques.
For
experienced
programmers,
the book demonstrates Python's breadth of
AddressBook.AddAddress("Bill", "555-1235")
capabilities
and
shows
the
ways
that
Python
interfaces with Java APIs for professional
AddressBook.AddAddress("Robert", "555-1257")
application development.
AddAddress()notifies all the listeners that an address has been added. (The listeners are the two JList
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
components.)
and Enterprise Applications with Jython covers important topics such as:
To run this example from the interactive interpreter, start JList_AddressModel.py with the i option. Then call
AddAddress() from the interactive interpreter.
Fundamental programming concepts, including statements, expressions,
>>> addNames() interpreters, and compilers

>>> frame.pack()

Python basics, including operators, string formatting, namespaces, classes, errors,


and
exceptions
Both of the lists are updated
because
they use the same example. (You have to call the frame.pack()
method to resize JList so that all of the items appear. We'll fix this in the next example).
Object-oriented programming concepts
As an exercise, look up javax.swing.ListModel,javax.ListDataEvent, and
File input/output
javax.ListDataListener
.
Python's
intrinsic
functions
Essentially, JList registers
for (that
is, subscribes
to) events in ListModel. When the model data changes
(that is, when addresses are added to the address book), all registered views are notified and thus updated.
Formatting, parsing, and manipulating strings
In the previous example, both views are JList components; however, in a real MVC application the same
Interfacing with the Java APIs and working with Java Streams
model may have more than one view type. For example, a spreadsheet application may have data mapped to a
spreadsheet view and a graph
view,
both and
of which
changetowhen
model for the spreadsheet view changes.
Using
Python
Java Swing
createthe
GUIs

Working with SQL and JDBC(TM)


Python and Java applets
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

An Easier Way to Create the Address Book

Publisher:
Addison
Wesley
An easier way to create
the address
book
is to use the AbstractListModel class, which
Pubmethods
Date: June
2002 event listeners and notifying them of changes. Here's the
implements all of the
for 28,
registering
changedJList_AddressModel
(JList_AddressModel2.py), which uses
ISBN: 0-201-61616-5
Table of
AbstractListModel
Pages: for
640the superclass of AddressBook.
Contents

class AddressBook(AbstractListModel):
Characterized by ease of use, richness of expression, and concise syntax, Python has
def remained
__init__(self):
a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
# Fillwhen
in used
some
sample data
the two languages,
in combination,
ideal for Web and distributed enterprise
self.list_items
application
development. = [Address("Darrell", "555-1212")]

...
...
This
tutorial begins with coverage of some of the basics of Python programming. Using
self.list_items.append(Address("Chris",
"555-1212"))
plenty
of skill-building exercises and interactive programming sessions,
this book will
help those new to programming develop an understanding of concepts and practical
# public
int getSize()
techniques.
For experienced
programmers, the book demonstrates Python's breadth of
# Returns
the the
length
the
list.with Java APIs for professional
capabilities
and shows
ways thatof
Python
interfaces
def application
getSize(self):
development.
return len(self.list_items)
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and
with Jython covers important
topics such as:
# Enterprise
public Applications
Object getElementAt(int
index)

# Returns the value at the specified index.


def getElementAt(self, index):
Fundamental programming concepts, including statements, expressions,
return self.list_items[index]
interpreters, and compilers

def AddAddress(self,
name,
number):
Python basics, including
operators,
string formatting, namespaces, classes, errors,
self.list_items.append(Address(name,
number))
and exceptions
start = len(self.list_items)
endObject-oriented
= len(self.list_items)
programming concepts
fireIntervalAdded(self, type, start, end)
File input/output
Notice that the code to implement AddressBook ( ListModel) is now significantly shorter. I recommend
Python's intrinsic
functions
using the AbstractListModel
class instead
of the ListModel interface, which I used simply to
explain MVC.
Formatting, parsing, and manipulating strings
Interfacing with
JavaDecorator
APIs and working
with Java
Streams
Working with JScrollPane
andthethe
Design
Pattern
Using Decorator
Python anddesign
Java Swing
GUIs which essentially adds a JFC frame
TheJList class uses Gamma's
patterntotocreate
add scrolling,
to a scroll pane by passing a JList instance to JScrollPane's constructor. Thus, the code changes from
Working with SQL and JDBC(TM)
this:
Python and Java applets

list = JList(AddressBook)
list2 = JList(AddressBook)
In addition, the book contains instructions for downloading and installing the Python
to this:

language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.

list = JScrollPane(JList(AddressBook))
Whether you are a sophisticated computer user new to programming or a serious
list2 = JScrollPane(JList(AddressBook)

application developer, Python Programming with the Java(TM) Class Libraries will
you insight
the power
of Python
and theand
know-how
to. put
it toyou
work.
That's all. The same give
technique
worksinto
for adding
scrolling
to JTree
JTable
When
run this in the
interactive interpreter, you don't have to call frame.pack() after you call addNames(). The names
show up automatically, and so do the scrollbars.

777

Now start JList_AddressModel2.py with the i option. Then call the AddAddress() method from the

interactive interpreter.
Python Programming

with the Java Class Libraries: A Tutorial for Building


Web and Enterprise Applications with Jython
addNames()
By Richard Hightower

>>>
>>> frame.pack()

Publisher: Addison Wesley

Summary
Table of
In thisContents
chapter,

Pub Date: June 28, 2002


ISBN: 0-201-61616-5

640of
we coveredPages:
the basics

AWT and JFC components, some of which are polymorphically related.


We also covered MVC, which, although advanced, is essential for working with some of the more interesting
byisease
use,learning
richnessabout
of expression,
andthe
concise
syntax,publishes
Python has
components of JFC. Characterized
Learning MVC
goodoffor
events, since
architecture
events to
remained
a
premier
programming
language
for
more
than
a
decade,
and
is
used by
views.
novices and professionals alike. In particular, its close relationship to Java(TM) makes
twoonlanguages,
when used
in combination,
ideal for
Web andtodistributed
enterprise
There's a lot more tothe
cover
JFC and AWT,
but we've
gleaned enough
information
get started.
We'll learn
application
development.
more in coming chapters.

This tutorial begins with coverage of some of the basics of Python programming. Using
CONTENTS
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
Object-oriented programming concepts
File input/output
Python's intrinsic functions
Formatting, parsing, and manipulating strings
Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs
Working with SQL and JDBC(TM)
Python and Java applets
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
CONTENTS
Web and Enterprise Applications with Jython
By Richard Hightower

Chapter 14. First


Swing Application, Layout, and Menus
Publisher: Addison Wesley
Pub Date: June 28, 2002

Putting Things Together


with Basic Java GUIs
ISBN: 0-201-61616-5
Table of
Adding an Input Form
Pages:for
640an Address Entry: The Prototype
Contents
Adding an Input Form for an Address Entry: First Cut
Characterized
ease
use, richness
of Application:
expression, andPrototype
concise syntax, Python has
Adding a Main
Windowbyfor
theofAddress
Book
remained a premier programming language for more than a decade, and is used by
Adding a Main Window: First Cut
novices and professionals alike. In particular, its close relationship to Java(TM) makes
Adding a Toolbar
and a Dialog
theinAddress
Bookideal
Application
the two languages,
whenfor
used
combination,
for Web and distributed enterprise
Menus
application development.
Layout Managers
This tutorial
begins with coverage of some of the basics of Python programming. Using
A GridBagLayout
Example
plenty of skill-building exercises and interactive programming sessions, this book will
Putting Things Together: Adding GridBagLayout to the Address Application
help those new to programming develop an understanding of concepts and practical
Summary techniques. For experienced programmers, the book demonstrates Python's breadth of

capabilities and shows the ways that Python interfaces with Java APIs for professional
Terms in This Chapter
application development.
Python
Libraries:
AbsoluteProgramming
positioning with the Java(TM) Class
Layout
managerA Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
Dialog
Main window
programming concepts,Modal
including statements, expressions,
HelperFundamental
function
interpreters, and compilers
Index
Separator
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
In the last chapter, we covered
Swing with short code snippets; in this chapter, we'll build an example Swing
application. Snippets are great for learning how to use an API, but to see how things really come together you
Object-oriented programming concepts
need a more involved example.
File input/output
We'll continue with the address
book application, but we'll start off with minimal features and add more as we
put the application together, gradually showing more of Java GUI programming like menus and layout
Python's intrinsic functions
managers. Before we add any features, though, we'll do a prototype in an interactive session to give you handson, instant gratification. Formatting, parsing, and manipulating strings
Interfacing with with
the Java Basic
APIs and working
Java Streams
Putting Things Together
Java with
GUIs
Using Python and Java Swing to create GUIs
As promised, we're going to extend the address book application with a GUI front end. For this extension we'll
useAddress5.py ,which is based
on Address4.py
from
Chapter 8 with a few changes, all within the
Working
with SQL and
JDBC(TM)
readAddresses() and writeAddresses() functions. One change is the use of
Python
andof
Java
ObjectOutputStream
instead
theapplets
Python pickle module; another is the introduction of the
__repr__ method for the Address class, which allows us to create address objects with eval and makes
In addition,
book contains instructions for downloading and installing the Python
the printing of dictionaries
more the
meaningful.
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
andtext_read_write()
numerous code samples make
this book
a useful learning experience.
As an exercise, run the
function
in readAddresses()
and
writeAddresses() in both files. What differences do you notice in the output? How are these differences
Whether
are a sophisticated
computer
user new
to programming
or a serious
related to __repr__
? Alsoyou
try creating
one instance
of Address
using
the eval function
and the return
application
developer,
Python
Programming
with
the
Java(TM)
Class
Libraries will
value from __repr__ of another instance.
give you insight into the power of Python and the know-how to put it to work.

Adding an Input Form for an Address Entry: The Prototype

777

In an interactive session, let's create a GUI form that can edit an address entry. We want a frame that holds text

field components, which


willProgramming
be used to gather
thethe
address
information.
We alsoAwant
an OK
which
Python
with
Java
Class Libraries:
Tutorial
forbutton,
Building
signifies that the userWeb
is done
the current
address.with Jython
andentering
Enterprise
Applications
By Richard Hightower

To get the layout for the frame components, we'll use a technique that layers components in a container. For this
we'll put the text fields Publisher:
in one panelAddison
and theWesley
OK button in another. The panels themselves are components that
we'll put in the frame. Pub Date: June 28, 2002
ISBN: 0-201-61616-5
The first
thing
Table
of we need to do is import the JFrame,JButton, and JTextField classes from

Pages: 640
javax.swing.
Contents

Characterized import
by ease of use,
richness of expression, and concise syntax, Python has
>>> from javax.swing
JFrame
remained
a
premier
programming
language
for more than a decade, and is used by
>>> from javax.swing import JButton,
JTextField
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the with
two languages,
in combination,
ideal
andand
distributed
enterprise
Next we create a frame
the titlebarwhen
set to used
"Address
Entry," create
an for
OKWeb
button
a panel to
hold it, set
the frame's layout to application
BorderLayout
, and add the panel to the south region of the frame. Then we pack the
development.
frame and look at the results.
This tutorial begins with coverage of some of the basics of Python programming. Using
>>> frame = JFrame("Address
Entry",
visible=1)
plenty of skill-building exercises
and interactive
programming sessions, this book will
>>> okay = JButton("OK")
help those new to programming develop an understanding of concepts and practical
>>> from javax.swing
import
JPanel
techniques. For
experienced
programmers, the book demonstrates Python's breadth of
>>> buttonbarcapabilities
= JPanel()
and shows the ways that Python interfaces with Java APIs for professional
>>> buttonbar.add(okay)
application development.

>>> from java.awt import BorderLayout


Python Programming with the Java(TM)BorderLayout.SOUTH)
Class Libraries: A Tutorial for Building Web
>>> frame.contentPane.add(buttonbar,
and
Enterprise
Applications
with
Jython
covers
important topics such as:
>>> frame.pack()

Adding Text FieldsFundamental programming concepts, including statements, expressions,


interpreters, and compilers
Now we want to add text fields to the frame. There may be many of them, and the frame is using
basics,
operators,
string
formatting,
namespaces,
classes,
errors,
BorderLayout, whichPython
can hold
onlyincluding
five components
(EAST
,WEST
,NORTH
,SOUTH, and
CENTER
).
and
exceptions
Therefore, we add the fields to another panel, which we place in the CENTER region of the frame. We'll use
GridLayout for the layout manager of the panel, which will lay the components out in a grid. As we add
Object-oriented
programming
concepts
fields, we'll label them so that
the user knows
what each one
represents. We'll do this by adding instances of the
Label class near the corresponding text field.
File input/output
ImportGridLayout, and create an instance of it that lays out components in a 2-by-2 grid. Create a panel to
Python's intrinsic functions
hold the text fields called contentPane. Set the layout of contentPane to the GridLayout instance.

>>>
>>>
>>>
>>>

Formatting, parsing, and manipulating strings

from java.awt import GridLayout


grid = GridLayout(2,2)
Interfacing with the Java APIs and working with Java Streams
contentPane = JPanel()
contentPane.setLayout(grid)
Using Python and Java Swing to create GUIs

Create a JTextField instance


nameand
. Import
the Label class, create an instance of it, and add it to
Workingcalled
with SQL
JDBC(TM)
contentPane. Add the name JTextField to the panel. Then pack the frame, and look at the results.
Python and Java applets

>>>
>>>
>>>
>>>
>>>
>>>
>>>

name = JTextField()
from java.swing
import
JLabel
In addition, the
book contains
instructions for downloading and installing the Python
contentPane.add(JLabel("Name"))
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
contentPane.add(name)
and numerous code samples make this book a useful learning experience.
frame.pack()
Whether you are a sophisticated computer user
new to programming or a serious
frame.contentPane.add(contentPane,
BorderLayout.CENTER)
application developer, Python Programming with the Java(TM) Class Libraries will
frame.pack()

give you insight into the power of Python and the know-how to put it to work.
Now use the same technique to add phone number and email text fields.

777

Add the phone number field.

>>> phoneNumber
= Programming
JTextField()
Python
with the Java Class Libraries: A Tutorial for Building
>>> contentPane.add(JLabel("Phone
Web and Enterprise ApplicationsNumber"))
with Jython
>>> contentPane.add(phoneNumber)
By Richard Hightower
Add the email field.

Publisher: Addison Wesley

Pub Date: June 28, 2002


>>> email = JTextField()
ISBN: 0-201-61616-5
>>>of contentPane.add(JLabel("eMail"))
Table

Pages:
640
>>> contentPane.add(email)
Contents
>>> frame.pack()

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
Adding Event novices
Handlers
and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
We could improve our
form by setting
the labels' alignment to the right, but pretty interfaces are only the start.
application
development.
For the form to be useful, we need to set up the event handlers. This is just the prototype, so the event handlers
will access the text field
datawith
but only
print of
it to
the console.
Thiscomponent
tutorial begins
coverage
some
of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
To set up the event handler
for the
button, we need
to define
an event handler
that takesand
onepractical
argument to
help those
newOK
to programming
develop
an understanding
of concepts
hold the event.
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
Create a function thatapplication
acts as an development.
event handler for the OK button.

>>> def okayHandler(event):


Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
...
global
name, email, phoneNumber
and Enterprise Applications with Jython covers important topics such as:
...
print (name.text, email.text, phoneNumber.text)
...
Fundamental programming concepts, including statements, expressions,
Register the okayHandler()
function
with the OK button's actionPerformed event property.
interpreters,
and compilers

>>> okay.actionPerformed
okayHandler
Python basics, =
including
operators, string formatting, namespaces, classes, errors,
and exceptions
Now we have a working prototype. Try it out by entering a name, a phone number, and an email address, and
then hit the OK button. Object-oriented programming concepts
input/output
Adding an InputFileForm
for an Address Entry: First Cut
Python's intrinsic functions
At this point, you probably feel comfortable with the concepts the prototype introduces. To incorporate these
concepts into the address book
program,
let's organize
our code into
a class called AddressForm. This class
Formatting,
parsing,
and manipulating
strings
extends the javax.swing.JFrame class, which makes it a JFrame.
Interfacing with the Java APIs and working with Java Streams
AddressForm is passed an instance of the Address class in its constructor. okayHandler()
Using Python
and Java
Swing from
to create
GUIs
populates the fields of the instance
with values
extracted
AddressForm
's text fields. Look at
Address6.py below and make sure to read all of the comments.
Working with SQL and JDBC(TM)

from javax.swing import JFrame, JButton, JTextField, JLabel, JPanel


Python and
Java applets
from java.awt import
BorderLayout,
GridLayout
# AddressForm Class.
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
# This class is used to edit an instance of the Address class
and numerous code samples make this book a useful learning experience.

class AddressForm(JFrame):
def __init__(self,
address):
Whether you are a sophisticated
computer user new to programming or a serious
"""Constructor
for Programming
the AddressForm
classClass
\nLibraries
""" will
application developer, Python
with the Java(TM)
#
Call
constuctor
give you insight into the power of Python and the know-how to put it to work.
JFrame.__init__(self, "Address Entry", visible=1)

777

# Declare private variables


self.__address = address #hold address to be edited

self.__name
= NONE
theLibraries:
private
name for
textfield
Python Programming
with the #hold
Java Class
A Tutorial
Building
self.__email
NONE
#hold
the private email textfield
Web and Enterprise=Applications
with Jython
self.__phoneNumber
= NONE #hold the private phone# field
By Richard Hightower
self.__init__CreateButtonBar()
Publisher: Addison Wesley
self.__init__CreateTextFieldPanel()
Pub Date: June 28, 2002

Table
of
def
Contents

ISBN: 0-201-61616-5

__init__CreateButtonBar(self):
Pages: 640
""" Create okay button, a panel for the button. \n """
"""
Add bythe
button
panel
to this
"""
Characterized
ease of
use, richness
of expression,
and frame.
concise syntax, Python has
okay
=
JButton("OK")
remained a premier programming language for more than a decade, and is used by
buttonbar
= JPanel()
novices and professionals
alike. In particular, its close relationship to Java(TM) makes
buttonbar.add(okay)
the two languages, when used in combination, ideal for Web and distributed enterprise
self.contentPane.add(buttonbar,
BorderLayout.SOUTH)
application development.
Set with
thecoverage
eventof handler
for of
the
okay
button.
This tutorial# begins
some of the basics
Python
programming.
Using
okay.actionPerformed
= self.__okayHandler
plenty of skill-building exercises and
interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical

def __init__CreateTextFieldPanel(self):
techniques. For experienced programmers, the book demonstrates Python's breadth of
"""
Set and
up shows
the the
email,
andJava
name
fields """
capabilities
ways thatphoneNumber
Python interfaces with
APIs text
for professional
application development.

# Create the panel and set the grid layout.


Python Programming
with thehas
Java(TM)
Class Libraries:
# The grid
a layout
of a A Tutorial for Building Web
and Enterprise
Jython covers
important topics such as:
# 3Applications
row by with
2 column
grid.

editPane = JPanel()
editPane.setLayout(GridLayout(3,2))
Fundamental programming concepts, including
statements, expressions,
self.contentPane.add(editPane,
BorderLayout.CENTER)
interpreters, and compilers

# Create the name textfield and add it and its

Python basics, including operators, string formatting, namespaces, classes, errors,


# associated label to the contentPane.
and exceptions

# Note that name is a member of AddressForm


self.__name
= JTextField()
Object-oriented
programming concepts
editPane.add(JLabel("Name"))
editPane.add(self.__name)
File input/output

Python's
intrinsic functions
# Create
the phoneNumber textfield and add it and its

# associated label to the contentPane.


Formatting,
parsing,
andphoneNumber
manipulating strings
# Note
that
is a member of AddressForm.

self.__phoneNumber = JTextField()
Interfacing with the Java APIs and working with Java Streams
editPane.add(JLabel("Phone Number"))
editPane.add(self.__phoneNumber)
Using Python and Java Swing to create GUIs
# Create
email textfield and add it and its
Working
with SQLthe
and JDBC(TM)
# associated label to the contentPane.
# and
Note
Python
Javathat
applets email is a member of AddressForm.
self.__email = JTextField()
In addition, the book contains instructions for downloading and installing the Python
editPane.add(JLabel("eMail"))
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
editPane.add(self.__email)
and numerous code samples make this book a useful learning experience.
self.pack()
Whether you are
a sophisticated
computer user
to programming
or a serious
#Defines
the
event handler
fornewthe
okay button
application
developer,
Python
Programming
with
the
Java(TM)
Class
Libraries will
def __okayHandler(self, event):
give
you
insight
into
the
power
of
Python
and
the
know-how
to
put
it
to
work.
"""Event handler for the okay button"""
print (self.__name.text, self.__email.text,
self.__phoneNumber.text)
Address.__init__(self.__address, self.__name.text,
self.__phoneNumber.text, self.__email.text)

777

print
self.__address
Python Programming
with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython

Try adding the abilityBytoRichard


edit theHightower
address lines of the Address class and to right-align the labels that describe
the text fields.
Publisher: Addison Wesley
Date: June 28,
2002
Adding a MainPubWindow
for
the Address Book Application:
ISBN: 0-201-61616-5
Prototype
Table of

Pages: 640
Contents

The main window will


have a list of
address
As youand
select
a name
fromPython
the list,has
an
Characterized
bynames
ease offrom
use,the
richness
of book.
expression,
concise
syntax,
AddressForm instance
pops
up
in
which
you
edit
the
Address
instance
corresponding
to
that
name.
remained a premier programming language for more than a decade, and is used by

novices and professionals alike. In particular, its close relationship to Java(TM) makes
As a rule, code written to access data shouldn't be in the same module with code written to build GUIs, so first
the two languages, when used in combination, ideal for Web and distributed enterprise
we have to break our code into separate modules:
application development.
This tutorial
begins
with
coverage
of some of the basics of Python programming. Using
AddressForm.py
holds the
AWT
version
of AddressForm
plenty of skill-building exercises and interactive programming sessions, this book will
those
to programming
Address7.pyhelp
holds
the new
address
data code develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities
andmain
shows
the ways
thatcode
Python interfaces with Java APIs for professional
AddressMain.py
holds the
window
of the
application development.
AddressFormPane.py holds the AWT panel version of AddressForm
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
The first step is creating
a frame thatApplications
acts as the main
and then
addingtopics
a list tosuch
it. Then
and Enterprise
with window
Jython covers
important
as: we pack the
frame and make it visible.
ImportJFrame and JList
from javax.swing.
Fundamental
programming concepts, including statements, expressions,
interpreters, and compilers

>>> from javax.swing import JFrame, JList


Python basics, including operators, string formatting, namespaces, classes, errors,
Create instances of JFrame
DefaultListModel, and create a JFC list using an instance of it.
and. Import
exceptions
Add the instance to the frame container.
Object-oriented programming concepts

>>>
>>>
>>>
>>>

frame = JFrame("Main Frame")


from javax.swing
import DefaultListModel
File input/output
addresses = JList(DefaultListModel())
Python's intrinsic functions
frame.contentPane.add(addresses)

Pack the frame, and make itFormatting,


visible. parsing, and manipulating strings

>>> frame.pack() Interfacing with the Java APIs and working with Java Streams
>>> frame.visible=1
Using Python and Java Swing to create GUIs

Adding Names

Working with SQL and JDBC(TM)

applets For this next part, we're going to add names to our list from
A list with no items is like Python
a pizza and
withJava
no toppings.
the dictionary that holds a collection of address entries.
In addition, the book contains instructions for downloading and installing the Python
language
and the(Run
Java itDevelopment
Kit (JDK).
Terminology,
explanations,
Import everything from
address7.py.
as a main module
to create
a clean setdefinitions,
of data files.)
and numerous code samples make this book a useful learning experience.

>>> from address7 import *


Whether you are a sophisticated computer user new to programming or a serious
Use the readAddresses()
function toPython
open the
testaddr.datwith
file,the
which
is full Class
of address
entries.
application developer,
Programming
Java(TM)
Libraries
will
give you insight into the power of Python and the know-how to put it to work.

>>> fname="c:\\dat\\testaddr.dat"
>>> dict = readAddresses(fname)

777

Iterate through the keys of the dictionary of address entries returned by readAddresses(), and add the

keys as names in thePython


list.
Programming

with the Java Class Libraries: A Tutorial for Building


Web and Enterprise Applications with Jython
name By
in
dict.keys():
Richard
Hightower

>>> for
... addresses.model.addElement(name)
...
Publisher: Addison Wesley
>>> frame.pack()
Pub Date: June 28, 2002

0-201-61616-5
Now our
listofhas the names ISBN:
from our
address application. The frame should look like Figure 14-1.
Table

Contents

Pages: 640

Figure 14-1. Address Book Names List


Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.

Adding

This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
and shows the ways that Python interfaces with Java APIs for professional
Event capabilities
Handlers
application development.

Next we need to add some functionality to our list. First we'll make the AddressForm instance pop up when
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
we select an item, so we need to define a list event handler. How do we know which one? Remember that you
and Enterprise Applications with Jython covers important topics such as:
can use the jinfo module to inspect a component's event properties. Or, if you remember which event listener a
component handles, you can inspect it.
Fundamental programming concepts, including statements, expressions,
For example, you may remember
that JList
handles ListSelectionListener, or you may haved
interpreters,
and compilers
looked up JList in the Java API documentation and seen the addListSelectionListener()
method, which is a dead giveaway.
Let's say
that weoperators,
remembered,
soformatting,
we can do namespaces,
the following:classes, errors,
Python basics,
including
string
and exceptions
ImportListSelectionListener from the javax.swing.event package.
Object-oriented programming concepts

>>> from javax.swing.event import ListSelectionListener


File input/output
Use the dir() function to list ListSelectionListener's methods.
Python's intrinsic functions

>>> dir(ListSelectionListener)
['valueChanged'] Formatting, parsing, and manipulating strings

Let's also say that we remember


that allwith
methods
of aAPIs
givenand
XListener
take an XEvent argument,
Interfacing
the Java
working withinterface
Java Streams
so we can inspect the interface of the event object that will be passed to our event handler.
Using Python and Java Swing to create GUIs
As an exercise look up the ListSelectionListener interface and the ListSelectionEvent
Working with SQL and JDBC(TM)
class in the Java API documentation.
ImportListSelectionEvent
and inspect its attributes with the dir()
Python andfrom
Javajavax.swing.event,
applets
function.
In addition, the book contains instructions for downloading and installing the Python
>>> from javax.swing.event
import ListSelectionEvent
language and the Java Development
Kit (JDK). Terminology, definitions, explanations,
>>> dir(ListSelectionEvent)
and numerous code samples make this book a useful learning experience.

['firstIndex', 'getFirstIndex', 'getLastIndex', getValueIsAdjusting',


Whether you are a sophisticated computer user new to programming or a serious
'valueIsAdjusting']
application developer, Python Programming with the Java(TM) Class Libraries will
Now that we understand
properties
for List
, we can
setthe
upknow-how
our event handler
up an
give the
youevent
insight
into the power
of Python
and
to put ittotopop
work.
AddressForm instance when an item in the list is clicked.

777

ImportAddressForm from the AddressForm module.

>>> from AddressForm


import with
AddressForm
Python Programming
the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython

Create an event handler


that gets
the selected item from the list, looks up the corresponding Address instance
By Richard
Hightower
in the dictionary, and passes it to the AddressForm instance, where it can be edited.
Publisher: Addison Wesley

>>> def itemSelected(event):


Date: June 28, 2002
...
list = Pub
event.source
ISBN: 0-201-61616-5
... Table ofname = list.selectedValue
640
... Contents
address =Pages:
dict[name]
...
form = AddressForm(address)
Characterized by ease of use, richness of expression, and concise syntax, Python has
...

remained a premier programming language for more than a decade, and is used by
novices
andthe
professionals
alike.
its close relationship to Java(TM) makes
Register the event handler
with
event property
ofIn
theparticular,
list.
the two languages, when used in combination, ideal for Web and distributed enterprise
>>> addresses.valueChanged
application development.= itemSelected
coverage
ofpops
someupofthat
the lets
basics
Python
programming.
Now, every time youThis
clicktutorial
on thebegins
listbox,with
a new
window
youofedit
the address.
So far, Using
so good,
plenty
of skill-building
andfiles
interactive
programming
sessions, this book will
but we've left out a few
things,
like reading exercises
and writing
and closing
the main window.
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
Adding a Main
Window: First Cut
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
We're going to create the main window for the address book application, which will have the list on the left side
of the framewhen Python
the userProgramming
selects an item,
it appears
in the Class
AddressForm
right side.
with
the Java(TM)
Libraries: A instance
Tutorial on
forthe
Building
Web To do
this we'll convert AddressForm
so that it extends
java.awt.Frame
.
and Enterprise Applications
with java.awt.Panel
Jython covers importantinstead
topics of
such
as:
We'll also need to add some code to initialize the text fields in the AddressForm class (in AddressForm.py)
so that every time an address is passed to AddressForm (that is, when the user selects a name in the list),
Fundamental
AddressForm shows that
Addressprogramming
instance. concepts, including statements, expressions,
interpreters, and compilers
Here is a listing of AddressForm in AddressFormPane.py:
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
from Address7 import
Address

...
Object-oriented
# AddressForm
Class. programming concepts
# This class is used to edit an instance of the Address class
File input/output
class AddressForm(JPanel):
...
Python's intrinsic functions
...
def set(self,
address):
Formatting,
parsing, and manipulating strings
"""Used to put a new address in this form
Initializes
all
text fields
with
Interfacing with the
Javaof
APIsthe
and working
with Java Streams
the attributes from self.__address.
""" Using Python and Java Swing to create GUIs
self.__address = address
Working with SQL and
self.__name.text
= JDBC(TM)
address.name()
self.__email.text = address.email()
Python and Java applets
self.__phoneNumber.text = address.phoneNumber()
... In addition, the book contains instructions for downloading and installing the Python
... language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.

def __init__CreateTextFieldPanel(self):
"""
Set
email,computer
phoneNumber
and name ortext
fields """
Whether
youup
are athe
sophisticated
user new to programming
a serious
...
...

application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

# Create the name textfield and add it and its


# associated label to the contentPane.

# Note that
is Class
a member
ofA Tutorial
AddressForm
Python Programming
withname
the Java
Libraries:
for Building
self.__name
= Applications
JTextField(self.__address.name())
Web and Enterprise
with Jython
editPane.add(JLabel("Name"))
By Richard Hightower

Table of
Contents

editPane.add(self.__name)
# Create
the phoneNumber textfield and add it and its
Publisher:
Addison Wesley
#
associated
Pub Date: June 28, 2002 label to the contentPane.
# Note
that phoneNumber is a member of AddressForm.
ISBN:
0-201-61616-5
self.__phoneNumber=JTextField(self.__address.phoneNumber())
Pages: 640
editPane.add(JLabel("Phone Number"))
editPane.add(self.__phoneNumber)
Characterized by ease of use, richness of expression, and concise syntax, Python has
# aCreate
the email
textfield
and
add and
it isand
its
remained
premier programming
language
for more than
a decade,
used by
#
associated
label
to
the
contentPane.
novices and professionals alike. In particular, its close relationship to Java(TM) makes
Note that
email
is a member
of and
AddressForm.
the two #languages,
when used
in combination,
ideal for Web
distributed enterprise
print
self.__address.email()
application
development.
self.__email = JTextField(self.__address.email())
editPane.add(JLabel("eMail"))
This tutorial begins with coverage of some of the basics of Python programming. Using
editPane.add(self.__email)
plenty of skill-building exercises and interactive programming sessions, this book will

help those new to programming develop an understanding of concepts and practical


Notice that I've added
extra functions
to the Address
classthe
email()
,name(), Python's
and
techniques.
For experienced
programmers,
book demonstrates
breadth of
phoneNumber()capabilities
to allow and
access
to the
variables
the Address
instance.
shows
theprivate
ways that
Pythonofinterfaces
with Java
APIs for professional
application development.

Moving Things Around


Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
Enterprise
with Jython
covers
Now let's change theand
application
so Applications
that the list shows
up on the
left important
side of thetopics
screensuch
and as:
the information shows
up on the right side. The next example, from AddressMain.py, shows the AddressMain class. Much of its
code was covered in the prototype
from programming
the last section.concepts, including statements, expressions,
Fundamental

interpreters, and compilers


Python basics, including operators, string formatting, namespaces, classes, errors,
andDon't
exceptionsOverdo the Comments
Object-oriented
I don't recommend using
comments programming
as I have here concepts
when you're writing real code. For more on
writing comments and maintainable code, read Enough Rope to Shoot Yourself in the Foot (Holub,
File input/output
1995).

from
from
from
from

javax.swing Python's
import
JFrame,
intrinsic
functionsJList, DefaultListModel
java.awt import BorderLayout
address7 import
* parsing, and manipulating strings
Formatting,
AddressFormPane import AddressForm
Interfacing with the Java APIs and working with Java Streams

class AddressMain(JFrame):
Using Python and Java Swing to create GUIs
def __init__(self):
# Call the base class constructor
Working with SQL and JDBC(TM)
JFrame.__init__(self, "Main Frame")
Python and Java applets

# Create a list.
= JList(DefaultListModel())
Inself.addresses
addition, the book contains
instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
# code
Addsamples
the make
addresses
to the
and numerous
this book alist
useful learning
experience.

# container, on the left side


Whether
you are a sophisticated computer user new to programming
or a serious
self.contentPane.add(self.addresses,
BorderLayout.WEST)
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight
into theup
power
of Python
and the know-how to put it to work.
# Open
the
file.

self.fname="c:\\dat\\testaddr.dat"
self.dict = readAddresses(self.fname)
# Populate the address list.
for name in self.dict.keys():

777

self.addresses.model.addElement(name)
Python Programming
with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
# Set the event handler for the addresses.
By Richard Hightower
self.addresses.valueChanged = self.__itemSelected
Publisher: Addison Wesley

Table of
Contents

Create
Pub Date:#June
28, 2002the AddressForm and add it to the EAST.
self.form
=
AddressForm()
ISBN: 0-201-61616-5
self.contentPane.add(self.form,
BorderLayout.EAST)
Pages: 640
# byPack
frameofand
makeand
itconcise
visible.
Characterized
ease ofthe
use, richness
expression,
syntax, Python has
self.pack()
remained a premier programming language for more than a decade, and is used by
self.visible=1
novices
and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
self.windowClosing
= self.__windowClosing
application
development.

def __itemSelected(self,
event):
This tutorial begins with coverage
of some of the basics of Python programming. Using
nameof =
event.source.selectedValue
plenty
skill-building
exercises and interactive programming sessions, this book will
address
help
those new=toself.dict[name]
programming develop an understanding of concepts and practical
#Notify
the
panel that
the
address
has breadth
changed
techniques. For
experienced
programmers,
the book
demonstrates
Python's
of
self.form.set(address)
capabilities
and shows the ways that Python interfaces with Java APIs for professional
application development.

def __windowClosing(self,event):
Python
Programming with the Java(TM) Class
Libraries: A Tutorial for Building Web
writeAddresses(self.fname,
self.dict)
and
Enterprise
Applications
with Jython
covers important topics such as:
from
java.lang
import
System
System.exit(0)
if __name__ == "__main__":
programming concepts, including statements, expressions,
mainWindowFundamental
= AddressMain()
interpreters, and compilers

If you run AddressMain.py, you should get a frame that looks like Figure 14-2. Notice that, when you click on a
Python basics, including operators, string formatting, namespaces, classes, errors,
name in the list, its fields are displayed in the form. You can edit the fields and then hit the Apply button. Also
and exceptions
notice that, when you change the names and then reload the application, the changed values are displayed.

Object-oriented programming concepts


Figure 14-2. Address Main Frame
File input/output
Python's intrinsic functions
Formatting, parsing, and manipulating strings
Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs
Working with SQL and JDBC(TM)

Changes in AddressMain.py

Python and Java applets


As for what's different in AddressMain.py, the most obvious thing is that all of the code is contained in a class.
In addition,
the book contains
instructions
downloading
We created an instance
of AddressForm
and added
it to thefor
main
frame. and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
numerous
code samples make
book
learning
experience.
# Createandthe
AddressForm
and this
add
ita useful
to the
EAST.

self.form = AddressForm()
Whether you are a sophisticated
computer user new to programming or a serious
self.container.add(self.form,
BorderLayout.EAST)
application developer, Python Programming with the Java(TM) Class Libraries will
give youininsight
thehandler.
power of
and thewe
know-how
putinstance
it to work.
Another difference appears
the listinto
event
InPython
the prototype,
created atonew
of
AddressForm and passed its constructor an address instance from the dictionary. Here we passed the
address instance from the dictionary to AddressForm'sset() function. The set() function changes
theaddress attribute of the AddressForm instance and initializes the text fields.

777

class AddressMain(Frame):
Python Programming with the Java Class Libraries: A Tutorial for Building
...
Web and Enterprise Applications with Jython
def __itemSelected(self,
event):
By Richard Hightower
if (event.stateChange == event.SELECTED):
=Wesley
event.itemSelectable.getItem(event.item)
Publisher:name
Addison
address
= self.dict[name]
Pub Date: June 28, 2002
#
Notify the panel that the address has changed
ISBN: 0-201-61616-5
Table of
self.form.set(address)

Pages: 640
Contents

class AddressForm(Panel):
Characterized by ease of use, richness of expression, and concise syntax, Python has
... remained a premier programming language for more than a decade, and is used by
... novices and professionals alike. In particular, its close relationship to Java(TM) makes
def set(self,
address):
the two languages,
when used in combination, ideal for Web and distributed enterprise
"""Used
to put a new address in this form
application
development.
Initializes all of the text fields with
the
attributes
from ofself.__address.
This
tutorial
begins with coverage
some of the basics of Python programming. Using
"""of skill-building exercises and interactive programming sessions, this book will
plenty
self.__address
= address
help
those new to programming
develop an understanding of concepts and practical
self.__name.text
= address.name()
techniques.
For experienced programmers,
the book demonstrates Python's breadth of
self.__email.text
capabilities
and shows the ways =
thataddress.email()
Python interfaces with Java APIs for professional
self.__phoneNumber.text
= address.phoneNumber()
application
development.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise
Applications
Jython
covers
important topics such as:
Where
to with
Find
the
Example
Throughout this chapter
and into the
next, we'll concepts,
return to this
AddressMain.py
make
Fundamental
programming
including
statements,and
expressions,
improvements to it. interpreters,
We'll put each
improvement
in
a
new
directory
within
the
current
chapter
and compilers
directory, so the next improvement will be in the One directory within the Chap14 directory of the
Web site's ExamplesPython
directory
(i.e.,including
C\JYTHONBook\Examples\Chap14\One).
basics,
operators, string formatting, namespaces, classes, errors,
and exceptions
We've created a GUI application that wins no prizes for beauty and grace but gets the job done. Now, as all good
programming concepts
programmers do, let's muckObject-oriented
with it.

File input/output

Adding a Toolbar and a Dialog for the Address Book Application


Python's intrinsic functions
We want to be able to add new addresses to the address list. Essentially, that means two new buttons, Add and
Formatting, parsing, and manipulating strings
Remove, which we'll put in a new panel in the north region of the main frame. (See Figure 14-3.) When the user
presses the Add button a dialog
pops up.
A the
dialog
like aand
frame,
except
thatJava
it's modal
(i.e., you have to close it
Interfacing
with
JavaisAPIs
working
with
Streams
before you can continue using your application).
Using Python and Java Swing to create GUIs
Figure 14-3. The Add and Remove Buttons
Working with SQL and JDBC(TM)

Python and Java applets


In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

The Dialog Class

The dialog class, AddAddressDialog


is in the
module
AddressMain
andfor
contains
an
Python Programming, with
thesame
Java
ClassasLibraries:
A Tutorial
Building
instance of the AddressForm
panel. It extends
java.awt.Dialog
.
Web and Enterprise
Applications
with Jython
By Richard Hightower

from java.awt import Dialog


class AddAddressDialog(Dialog):
Publisher: Addison Wesley
...
Pub Date: June 28, 2002
...

ISBN: 0-201-61616-5
Table of
Pages:
640
AddAddressDialog
gets most
of its functionality from
Contents

AddressFormPane, which it contains, and


adds two buttons, OK and Cancel, which appear on a panel that acts as a toolbar. (See Figure 14-4.) The toolbar
easeThe
of use,
richness of expression,
and concise
syntax,
Python
is placed in the southCharacterized
region of the by
panel.
AddressFormPane
instance
is placed
in the
centerhas
region.
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
Figure 14-4. The Okay and Cancel Buttons
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

class AddAddressDialog(JDialog):
...
Fundamental programming concepts, including statements, expressions,
...
interpreters, and compilers
def __init__(self, frame):
... Python basics, including operators, string formatting, namespaces, classes, errors,
... and exceptions
# Create
a dialog
box and add the AddressForm to it.
Object-oriented
programming
concepts
self.contentPane.add(self.__form, BorderLayout.CENTER)
File input/output

# Create a toolbar with two buttons and


Python's
intrinsic
# add
itfunctions
to the south part of the dialog

toolbar = Panel()
Formatting, parsing, and manipulating strings
ok = Button("OK")
cancel
= Button("Cancel")
Interfacing
with the Java APIs and working with Java Streams
toolbar.add(ok)
toolbar.add(cancel)
Using Python and Java Swing to create GUIs
ok.actionPerformed = self.__okEventHandler
cancel.actionPerformed
= self.__cancelEventHandler
Working with SQL and JDBC(TM)
self.contentPane.add(toolbar, BorderLayout.SOUTH)
Python and Java applets
Pressing the OK button hides the dialog, saves its state, and invokes a commit() method that commits the
In addition, the
book contains instructions for downloading and installing the Python
changes to the AddressForm
instance.
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
class AddAddressDialog(JDialog):
and numerous code samples make this book a useful learning experience.

OK = 0
CANCEL Whether
= 1 you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
...
give you insight into the power of Python and the know-how to put it to work.
...
def __okEventHandler(self,event):
self.visible = 0
self.__state = AddAddressDialog.OK
self.__form.commit()

777

class AddressForm(Panel):
Python Programming with the Java Class Libraries: A Tutorial for Building
...
Web and Enterprise Applications with Jython
...
By Richard Hightower
def commit(self):
self.__address.__init__(self.__name.text,
Publisher: Addison Wesley
self.__phoneNumber.text,
self.__email.text, [])
Pub Date: June 28, 2002
ISBN: 0-201-61616-5

Table
Pressing
theofCancel button hides the dialog and saves its state.

Contents

Pages: 640

class AddAddressDialog(JDialog):
OK = 0Characterized by ease of use, richness of expression, and concise syntax, Python has
CANCELremained
= 1 a premier programming language for more than a decade, and is used by
novices
... and professionals alike. In particular, its close relationship to Java(TM) makes
the
two languages, when used in combination, ideal for Web and distributed enterprise
...
application
development.
def __cancelEventHandler(self,event):
self.visible = 0
This tutorial begins with coverage of some of the basics of Python programming. Using
self.__state = AddAddressDialog.CANCEL

plenty of skill-building exercises and interactive programming sessions, this book will
help those
to programming
develop an ,understanding
concepts
practical
AddAddressDialog
has anew
method
called GetState()
which returns of
whether
theand
dialog
was closed
techniques.
For
experienced
programmers,
the
book
demonstrates
Python's
of
with OK or Cancel, and a method called getAddress(), which returns the new addressbreadth
instance.
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
class AddAddressDialog(JDialog):

OK = 0
CANCELPython
= 1Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and
Enterprise Applications with Jython covers important topics such as:
...
def GetState()(self):
return
self.__state
Fundamental
programming concepts, including statements, expressions,
interpreters, and compilers

def getAddress()(self):
return
Pythonself.__address
basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
Here is the complete listing for AddAddressDialog (from One\AddressMain.py):
Object-oriented programming concepts

from java.awt import BorderLayout


from javax.swing File
import
JFrame, JList, DefaultListModel, JPanel, JDialog,
input/output
JButton
Python's
from address import
* intrinsic functions
from AddressFormPane import AddressForm
Formatting, parsing, and manipulating strings
class AddAddressDialog(JDialog):
OK = 0
CANCEL = 1Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs

def __init__(self, frame):


JDialog.__init__(self,
frame, "Add a new address")
Working with SQL and JDBC(TM)
self.__address
= Address() #hold the address to be added.
Python and Java applets
self.__form = AddressForm(self.__address)
In addition, the book contains instructions for downloading and installing the Python
language and#theCreate
Java Development
Kit (JDK).
definitions,
explanations, to it.
a dialog
box Terminology,
and add the
AddressForm
and
numerous code samples make this book a useful learning
experience.
self.contentPane.add(self.__form,
BorderLayout.CENTER)
Whether you#areCreate
a sophisticated
computer user
new two
to programming
serious
a toolbar
with
buttonsor aand
application developer,
Python
Programming
with
the
Java(TM)
Class
Libraries
# add it to the south part of the dialog will
give
you
insight
the power of Python and the know-how to put it to work.
toolbar = into
JPanel()

ok = JButton("OK")
cancel = JButton("Cancel")
toolbar.add(ok)
toolbar.add(cancel)

777

ok.actionPerformed
= Java
self.__okEventHandler
Python
Programming with the
Class Libraries: A Tutorial for Building
cancel.actionPerformed
= self.__cancelEventHandler
Web
and Enterprise Applications with
Jython
self.contentPane.add(toolbar,
BorderLayout.SOUTH)
By
Richard Hightower

Table of
Contents

PackWesley
it, make it modal, and show it
Publisher:#Addison
self.setModal(1)
Pub Date: June 28, 2002
self.pack()
ISBN: 0-201-61616-5
self.show()
Pages: 640

def __okEventHandler(self,event):
Characterized by ease of use, richness of expression, and concise syntax, Python has
self.__state
= AddAddressDialog.OK
remained
a premier programming
language for more than a decade, and is used by
self.__form.commit()
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise

def __cancelEventHandler(self,event):
application development.
self.visible = 0
self.__state
= coverage
AddAddressDialog.CANCEL
This
tutorial begins with
of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will

def GetState(self):
help those new to programming develop an understanding of concepts and practical
return For
self.__state
techniques.
experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional

def getAddress()(self):
application development.
return self.__address

Adding the

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
Toolbar

Remember that the dialog is


opened in response
to a click
of the including
Add button.
Let's takeexpressions,
a look at Add in a partial
Fundamental
programming
concepts,
statements,
listing of AddressMaininterpreters,
with the toolbar
added.
and compilers

class AddressMain(JFrame):
Python basics, including operators, string formatting, namespaces, classes, errors,
def __init__(self):
and exceptions
# Call the base class constructor
JFrame.__init__(self,
"Main Frame")
Object-oriented programming concepts
... File input/output
...

Python's intrinsic functions


self.__init__toolbar()
Formatting, parsing, and manipulating strings

...
... Interfacing with the Java APIs and working with Java Streams
def __init__toolbar(self):
Using Python and Java Swing to create GUIs
# Create
the
toolbar panel and
Working
with SQL and
JDBC(TM)
# add it to the NORTH border of the container.
Python and
Java applets
toolbar
= JPanel()
self.contentPane.add(toolbar, BorderLayout.NORTH)

In addition, the book contains instructions for downloading and installing the Python
language and#theCreate
Java Development
Kit (JDK). Terminology, definitions, explanations,
two buttons
and
numerous
code
samples
make
this
book a useful learning experience.
addAddress = JButton("Add")

removeAddress = JButton ("Remove")

Whether you are a sophisticated computer user new to programming or a serious


application developer, Python Programming with the Java(TM) Class Libraries will
# Add the buttons to the toolbar
give you insight into the power of Python and the know-how to put it to work.

toolbar.add(addAddress)
toolbar.add(removeAddress)

777

# Registers the buttons event handler

addAddress.actionPerformed=self.__addAddress_Clicked
Python
Programming with the Java Class Libraries: A Tutorial for Building
removeAddress.actionPerformed=self.__RemoveAddress_Clicked
Web
and Enterprise Applications with Jython
By Richard Hightower

def __addAddress_Clicked(self,event):
dialog
AddAddressDialog(self)
Publisher:=Addison
Wesley
ifPubdialog.GetState()
== AddAddressDialog.OK:
Date: June 28, 2002
addr
=
dialog.getAddress()
ISBN: 0-201-61616-5
Table of
self.dict[addr.name()] = addr
Pages: 640
Contents
self.addresses.add(addr.name())
else:
Characterized by ease of use, richness of expression, and concise syntax, Python has
printprogramming
"Cancel language
Add: "
`dialog.getAddress()`
remained a premier
for +more
than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes

def __RemoveAddress_Clicked(self,event):
the two languages, when used in combination, ideal for Web and distributed enterprise
index =development.
self.addresses.selectedIndex
application
key = self.addresses.selectedItem
deltutorial
self.dict[key]
This
begins with coverage of some of the basics of Python programming. Using
self.addresses.remove(key)
plenty
of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
# Get
the programmers,
index of the
the
item
before
thisbreadth
one.of
techniques. For
experienced
book
demonstrates
Python's
# Unless
the that
index
the with
item
removed
is 0.
capabilities and
shows the ways
Pythonof
interfaces
Javawe
APIs
for professional
application development.

if index-1 < 0: index = 0


else:
index =with
index
-1 Class Libraries: A Tutorial for Building Web
Python
Programming
the Java(TM)
and Enterprise Applications with Jython covers important topics such as:
# Select the index of the adjacent item.
if len(self.dict.keys()) > index:
Fundamental
concepts, including statements, expressions,
printprogramming
self.dict.keys()[index]
interpreters,
and compilers
self.addresses.select(index)
# set the form to the index
Python basics, including operators, string formatting, namespaces, classes, errors,
# that we selected in the list
and exceptions
address = self.dict[self.dict.keys()[index]]
self.form.set(address)
Object-oriented
programming concepts
The__init__toolbar
method
creates a toolbar and adds it to the north region of the main frame. Then it
File
input/output
instantiates two buttons and adds them to the toolbar. The Add and Remove buttons are registered with the event
handler methods. __addAddress_Clicked
and __RemoveAddress_Clicked .
Python's intrinsic functions

def __init__toolbar(self):
Formatting, parsing, and manipulating strings
Interfacing
with thethe
Java APIs
and working
with and
Java Streams
# Create
toolbar
panel

# add it to the NORTH border of the container.


Using =Python
and Java Swing to create GUIs
toolbar
Panel()
self.container.add(toolbar, BorderLayout.NORTH)
Working with SQL and JDBC(TM)

# and
Create
two buttons
Python
Java applets
addAddress = Button("Add")
removeAddress
= Button
("Remove")
In addition, the book contains
instructions
for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
# Add
the buttons
to athe
and numerous
code samples
make this book
usefultoolbar
learning experience.

toolbar.add(addAddress)
toolbar.add(removeAddress)
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
# Registers
buttons
event handler
give you insight
into the powerthe
of Python
and the know-how
to put it to work.

addAddress.actionPerformed=self.__addAddress_Clicked
removeAddress.actionPerformed=self.__RemoveAddress_Clicked

777

Adding and Removing Addresses

Python Programming with the Java Class Libraries: A Tutorial for Building

The__addAddress_Clicked
event Applications
handler is where
theJython
AddAddressDialog class is used. It
Web and Enterprise
with
creates an instance ofByAddAddressDialog
called
dialog
. After the user opens the dialog to enter an
Richard Hightower
address (or not), the method checks to see if the OK button was pressed by calling dialog'sGetState()
method. If the OK state Publisher:
is set, the address
added to the address dictionary ( dict) and the address list
AddisonisWesley
(addresses).
Pub Date: June 28, 2002
ISBN: 0-201-61616-5

def Table
__addAddress_Clicked(self,event):
of

Pages: 640
Contents
dialog = AddAddressDialog(self)
if dialog.GetState() == AddAddressDialog.OK:
Characterized by ease of use, richness of expression, and concise syntax, Python has
addr = dialog.getAddress()
remained a premier programming language for more than a decade, and is used by
self.dict[addr.name()] = addr
novices and professionals alike. In particular, its close relationship to Java(TM) makes
self.addresses.add(addr.name())
the two languages, when used in combination, ideal for Web and distributed enterprise
else:
application development.
print "Cancel Add: " + `dialog.getAddress()`
This tutorial begins with coverage of some of the basics of Python programming. Using
Clicking the Remove button calls __RemoveAddress_Clicked(). This method is a little long, so we'll
plenty of skill-building exercises and interactive programming sessions, this book will
go through it step by step.
help those new to programming develop an understanding of concepts and practical
techniques.
For experienced
the book demonstrates
breadth
First, we get the index
of the selected
item in the programmers,
address list (addresses
). Then wePython's
get the value
of of
the
capabilities
and
shows
the
ways
that
Python
interfaces
with
Java
APIs
for
professional
string at that index, which is the name of the person in the address entry.
application development.

index = self.addresses.selectedIndex
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
key = self.addresses.selectedItem
and Enterprise Applications with Jython covers important topics such as:
Now we can remove the person from the address dictionary (dict) and from the address list.
Fundamental programming concepts, including statements, expressions,
del self.dict[key]
interpreters, and compilers
self.addresses.remove(key)
Python
basics,
including
string
formatting,
errors,
Next we need to select another
person
in the
list andoperators,
reinitialize
the address
formnamespaces,
so that both classes,
are synchronized.
and
exceptions
This means that we have to get the index of the item before this one, unless the index of the item we removed is
0.
Object-oriented programming concepts

if index-1 < 0: index = 0


File input/output
else: index = index -1
Python's intrinsic functions
Then we select the index of the adjacent item in the list and the form. We also do some sanity checking to see if
the dictionary has enough items
in itthat
is, that
index value strings
is no greater than the number of items in the
Formatting,
parsing,
andthe
manipulating
dictionary.
Interfacing with the Java APIs and working with Java Streams

if len(self.dict.keys()) > index:

Using Python and Java Swing to create GUIs


Select the address in the list.
Working with SQL and JDBC(TM)

self.addresses.select(index)

Python and Java applets


Get the address instance from the dictionary; then select the address in the form.
In addition, the book contains instructions for downloading and installing the Python
address = self.dict[self.dict.keys()[index]]
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
self.form.set(address)
and numerous code samples make this book a useful learning experience.
The following line ofWhether
code does
lot and
may be hardcomputer
to understand:
youa are
a sophisticated
user new to programming or a serious

application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

address = self.dict[self.dict.keys()[index]]
Essentially, it's equivalent to writing these three lines of code:

777

listAddressNames = self.dict.keys()
currentAddressKey = listAddressNames[index]

address = self.dict[currentAddressKey]
Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython

Here's what it meansBy


step
by step:
Richard
Hightower
Get the dictionary keys, which act as a list of names from address instances.
Publisher: Addison Wesley

Pub Date:
June 28, 2002
listAddressNames
= self.dict.keys()
Table of

ISBN: 0-201-61616-5

Get the
name corresponding
to the640
value of the index, which is the address closest to the address just removed.
Pages:
Contents

currentAddressKey
= listAddressNames[index]
Characterized
by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
Use that name as a key
into the
to getalike.
the address
instances
the address
that was
novices
anddictionary
professionals
In particular,
its closecorresponding
relationship totoJava(TM)
makes
next to the address just
the removed.
two languages, when used in combination, ideal for Web and distributed enterprise
application development.

address = self.dict[currentAddressKey]
This tutorial begins with coverage of some of the basics of Python programming. Using
Set the AddressForm instance, form, to the new address.
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
self.form.set(address)
techniques. For experienced programmers, the book demonstrates Python's breadth of
and showsofthe
ways
thatand
Python
interfaces
withrun
Java
APIs for professional
Now that you have acapabilities
good understanding
how
to add
remove
addresses,
AddressMain.py,
and try
application development.
these exercises:
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
Add and remove
couple of address
entries.
GetJython
the feel
for how
the program
because you'll need it
andaEnterprise
Applications
with
covers
important
topics works
such as:
for the rest of the exercises.
programming
concepts,
including
statements,
expressions,
Add a company fieldFundamental
and a title field
to the Address
class.
You'll need
an extra
text field in the
interpreters,
AddressForm class
for this. and compilers
basics, including
operators,
string
namespaces,
classes,
Add a flag argumentPython
called isDialog
in the
constructor
of formatting,
AddressForm
that allows
youerrors,
to forgo
and
exceptions
adding the Apply button to the form. This flag will be used when the form acts as a dialog. Also, change
the background color of the dialog to match the background color of the address form.
Object-oriented programming concepts
Add two buttons to the toolbar of MainAddressForm. The Copy button (copyAddress) should
File input/output
copy the current selected
address. The Insert button (insertAddress) should insert the address into
the list.
Python's intrinsic functions

Menus

Formatting, parsing, and manipulating strings

Interfacing with the Java APIs and working with Java Streams
In Java there are two types of menus: menubar and popup. The following section shows how to add a menubar
to a frame.
Using Python and Java Swing to create GUIs

JMenu Bar

Working with SQL and JDBC(TM)

Python and Java applets


Import the JMenuBar class from java.swing.
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
Create an instance ofand
it. numerous code samples make this book a useful learning experience.

>>> from javax.swing import JJMenuBar

Whether you are a sophisticated computer user new to programming or a serious


>>> bar = JJMenuBar()
application developer, Python Programming with the Java(TM) Class Libraries will
you insight
into the
Import and create angive
instance
of JFrame
. power of Python and the know-how to put it to work.

>>> from javax.swing import JFrame


>>> frame = JFrame()

777

Set the JMenuBarPython


propertyProgramming
of the frame towith
the JMenuBar
instance.
the Java Class
Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython

>>> frame.JJMenuBar
= bar
By Richard Hightower
>>> frame.visible=1
Publisher: Addison Wesley

Now that we have a menubar added in the frame, we need to add a menu to it. Create a menu ( JMenu), and
Pub Date: June 28, 2002
add it to the menubar.

>>>

ISBN: 0-201-61616-5
Table of
Pages:
from javax.swing 640
import JMenu
Contents

>>> fruitMenu = JMenu("Fruit")


Characterized by ease of use, richness of expression, and concise syntax, Python has
>>> bar.add(fruitMenu)
remained a premier programming language for more than a decade, and is used by
>>> frame.pack()
novices and professionals alike. In particular, its close relationship to Java(TM) makes
themenu.
two languages, when used in combination, ideal for Web and distributed enterprise
Add menu items to the
application development.

>>>
>>>
>>>
>>>

from javax.swing import JMenuItem


fruitMenu.add(MenuItem("Apple"))
This tutorial begins with coverage of some of the basics of Python programming. Using
fruitMenu.add(JMenuItem("Pear"))
plenty of skill-building exercises and interactive programming sessions, this book will
fruitMenu.add(JMenuItem("Peaches"))
help those new to programming develop an understanding of concepts and practical

Menus Event

techniques. For experienced programmers, the book demonstrates Python's breadth of


capabilities and shows the ways that Python interfaces with Java APIs for professional
Handling
application development.

The menu just created


should
look like the with
one in
14-5Class
(if not,
try manually
resizingforthe
frame).Web
It's pretty,
Python
Programming
theFigure
Java(TM)
Libraries:
A Tutorial
Building
but it doesn't do anything.
We
need
to
handle
events
from
the
menu
or
menu
items.
and Enterprise Applications with Jython covers important topics such as:
Figure 14-5. The Fruit Menu
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers

Python basics, including operators, string formatting, namespaces, classes, errors,


and exceptions
Object-oriented programming concepts
File input/output
Python's intrinsic functions
Define an event handler.

Formatting, parsing, and manipulating strings

>>> def actionPerformed(event):


Interfacing with the Java APIs and working with Java Streams
...
print event.source
...
print event.paramString()
Using Python and Java Swing to create GUIs
...
print event.actionCommand
...
Working with SQL and JDBC(TM)

Get the Apple menu from the Fruit menu. It's the first one, so it's at index 0.
Python and Java applets

>>> appleMenu = fruitMenu.getMenuComponent(0)

In addition, the book contains instructions for downloading and installing the Python
language andevent
the Java
Development
Kit (JDK). Terminology,
definitions, explanations,
Set the actionPerformed
property
to actionPerformed
.
and numerous code samples make this book a useful learning experience.

>>> appleMenu.actionPerformed = actionPerformed

Whether you are a sophisticated computer user new to programming or a serious


application
developer,
Python
Programming
with the
Classoutput
Libraries
Try selecting the Apple
menu item
in the Fruit
menu
again. You should
getJava(TM)
the following
fromwill
the event
give
you
insight
into
the
power
of
Python
and
the
know-how
to
put
it
to
work.
handler we just defined:

javax.swing.JMenuItem[...]
ACTION_PERFORMED,cmd=Apple
Apple

777

Python Programming
with
the Java
Class
Libraries:
A Tutorial
for Building
Notice that actionCommand
is a string set
to Apple
. Now
try selecting
Pear
and Peaches
. Nothing
Web
and
Enterprise
Applications
with
Jython
happens because we didn't register event handlers for them.
By Richard Hightower

Set the event handlers for all menu items.


Publisher: Addison Wesley

>>> for menuItem


in fruitMenu.menuComponents:
Pub Date:
June 28, 2002
...
menuItem.actionPerformed
= actionPerformed
ISBN: 0-201-61616-5
... Table of
Pages: 640
Contents

SelectPear and Peaches again.


Characterized by ease of use, richness of expression, and concise syntax, Python has
premiermenu
programming
language
for more
thanThen
a decade,
is useditems
by to it and
In this next exampleremained
we'll add aanother
to JMenuBar
called
Veggies.
we'll and
add menu
novices
and
professionals
alike.
In
particular,
its
close
relationship
to
Java(TM)
makes
handle events from specific items instead of from the menu as a whole.
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
Create the Veggies menu.

This tutorial
begins with coverage of some of the basics of Python programming. Using
>>> veggiesMenu
= JMenu("Veggies")
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
Create three menu items.
techniques. For experienced programmers, the book demonstrates Python's breadth of
>>> spinach =capabilities
JMenuItem("Spinach")
and shows the ways that Python interfaces with Java APIs for professional
>>> carrots =application
JMenuItem("Carrots")
development.

>>> peas = JMenuItem("Peas")


Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
Define event handlers
forEnterprise
each menuApplications
item and register
them. covers important topics such as:
and
with Jython

>>> def spinachEvent(event):


...
print "You Fundamental
Picked Spinach"
programming concepts, including statements, expressions,
interpreters, and compilers

>>> spinach.actionPerformed = spinachEvent


Python basics, including operators, string formatting, namespaces, classes, errors,
>>> def carrotEvent(event):
and exceptions
...
print "What's
up DOC?"
>>> carrots.actionPerformed = carrotEvent
Object-oriented programming concepts

>>> def peaEvent(event):


File input/output
...
print "Yuck!"
>>> peas.actionPerformed
= functions
peaEvent
Python's intrinsic
Add the menu items to the Formatting,
Veggies menu.
parsing, and manipulating strings

>>> veggiesMenu.add(spinach)
Interfacing with the Java APIs and working with Java Streams
>>> veggiesMenu.add(carrots)
>>> veggiesMenu.add(peas)
Using Python and Java Swing to create GUIs
Add the Veggies menu to the
menubar.
Working
with SQL and JDBC(TM)

>>> bar.add(veggiesMenu)
Python and Java applets
>>> frame.pack()
In addition, the book contains instructions for downloading and installing the Python
Select each menu item;
noticeand
thatthe
its handler
is called. Kit (JDK). Terminology, definitions, explanations,
language
Java Development
and numerous code samples make this book a useful learning experience.

You Picked Spinach


What's up DOC?
Whether you are a sophisticated computer user new to programming or a serious
Yuck!
application developer, Python Programming with the Java(TM) Class Libraries will

give you insight into the power of Python and the know-how to put it to work.
Now we'll add cooking options to the Veggies menu so that, once the user selects an option (Fry, Broil, Boil,
Roast), he can select the Cook menu item to prepare the veggies accordingly. The exercise that follows will use
separators and checkboxes.

777

Add a separator to the


end ofProgramming
the Veggies menu
using
addSeparator()
Python
with
the the
Java
Class Libraries: A method.
Tutorial for Building
Web and Enterprise Applications with Jython

>>> veggiesMenu.addSeparator()
By Richard Hightower
Add a submenu to Veggies by creating cookMenu and adding it to veggiesMenu.
Publisher: Addison Wesley

Date: June 28, 2002


>>> cookMenu = Pub
JMenu("Cooking")
ISBN: 0-201-61616-5
>>> Table
veggiesMenu.add(cookMenu)
of

Contents

Pages: 640

Add a menu item to cookMenu called Cook.


Characterized by ease of use, richness of expression, and concise syntax, Python has
>>> cookMenuItem
= aJMenuItem("Cook")
remained
premier programming language for more than a decade, and is used by
>>> cookMenu.add(cookMenuItem)
novices and professionals alike. In particular, its close relationship to Java(TM) makes
>>> cookMenu.insertSeparator(cookMenu.itemCount)
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
Now we'll demonstrate creating and using checkboxes.
This tutorial begins with coverage of some of the basics of Python programming. Using
ImportJCheckboxMenuItem
from javax.swing.
plenty of skill-building
exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
>>> from javax.swing import JCheckBoxMenuItem
techniques. For experienced programmers, the book demonstrates Python's breadth of
and shows
the waystothat
interfaces
with
JavatoAPIs
for professional
Create a list of item capabilities
names, and create
a dictionary
holdPython
mappings
from the
items
the names.
application development.

>>> cookItems = ('Fry', 'Broil', 'Boil', 'Roast')


>>> dict ={} Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
Add each item in the above list to the Cook menu (cookMenu ). In addition, add the item to the dictionary so it
can be found easily.
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
>>> for item in cookItems:

...
...
...

cb = JCheckBoxMenuItem(item)
Python basics, including operators, string formatting, namespaces, classes, errors,
dict[item]=cb
and exceptions
cookMenu.add(cb)

Object-oriented programming concepts


Now let's set up the event handler, cookOptionEvent, to handle these checkbox menu items. For clarity,
let's go through it step by step.
currently selected menu item's caption is equal to event.item. If it's
File The
input/output
Broil, event.item is Broil.
Python's intrinsic functions

...

if event.item in cookItems:

Formatting, parsing, and manipulating strings


Iterate through each item in cookItems, which you'll recall holds all of the possible cooking options.
Interfacing with the Java APIs and working with Java Streams

...

for item in cookItems:

Using Python and Java Swing to create GUIs


If the item in cookItemsisn't the current item, make sure its checkbox isn't selected.
Working with SQL and JDBC(TM)

...
...
...

if (item != event.item):
cb Python
= dict[item]
and Java applets
cb.state = 0

In addition, the book contains instructions for downloading and installing the Python
The statement cb =language
dict[item]
looks
up the JCheckboxMenuItem
in theexplanations,
dictionary that
and the Java
Development
Kit (JDK). Terminology,instance
definitions,
contains mappings ofand
strings
to
menu
items.
The
statement
cb.state
=
0
sets
the
state
of
the
numerous code samples make this book a useful learning experience.
JCheckBoxMenuItem instance (cb) to false, which removes its check.
Whether you are a sophisticated computer user new to programming or a serious
Now we need to set application
up the eventdeveloper,
handler forPython
cookMenuItem
Programming. with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

>>> def cookEvent(event):


...
for item in cookItems:
...
if dict[item].state:
...
print "I will " + item + " your veggies"

777

>>> cookMenuItem.actionPerformed
cookEvent
Python Programming with the =
Java
Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython

At this point, the menu


in your Hightower
frame should look like the one in Figure 14-6. If it doesn't, try resizing it.
By Richard
Figure
14-6.Addison
The Veggies
Publisher:
Wesley Menu with the Cooking Submenu
Pub Date: June 28, 2002

ISBN: 0-201-61616-5

Table of
Contents

Pages: 640

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
Now try selecting Fry and then
Cook. You programming
should get theconcepts
following output:
Object-oriented

I will Fry your veggies


File input/output
Then try Broil and Boil.

Python's intrinsic functions

I will Broil yourFormatting,


veggies
parsing, and manipulating strings
I will Boil your veggies
Interfacing with the Java APIs and working with Java Streams
Here are some more things to try:
Using Python and Java Swing to create GUIs
Convert the previousWorking
interactive
session
into JDBC(TM)
a class that contains all of the functionality derived from
with
SQL and
Frame. Remember how we converted an earlier interactive session that worked with Frame into a
class.
Python and Java applets
Change the code
to use JRadioButtonMenuItem
. Remember
fromand
Chapter
13 that
In addition,
the book contains instructions for
downloading
installing
theJMenuItem
Python
andJRadioButtonMenuItem
inherit
functionality
from
AbstractButton
.
Hint:
Add all of
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
theJRadioButtonMenuItem
s
to
ButtonGroup
.
and numerous code samples make this book a useful learning experience.
Add icons to the
variousyou
menu
Whether
are items.
a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
Set the mnemonics
of the
JFC into
menutheitems.
give you
insight
power of Python and the know-how to put it to work.

JPopupMenus

777

Popup menus are context-sensitive. Typically, they appear when you right-click an icon or component. The

following example demonstrates


popup menus.
Using
JFC creates
frame with Atwo
buttons:for
Switch
and Pop.
Python Programming
with
the Java
Classa Libraries:
Tutorial
Building
Web and Enterprise Applications with Jython

ImportJPopupMenu
and all Hightower
of its support classes from javax.swing.
By Richard

>>> from javax.swing import JPopupMenu


Publisher: Addison Wesley
>>> from javax.swing import JFrame, JButton, JPanel, JLabel
Pub Date: June 28, 2002

ISBN: 0-201-61616-5
CreateTable
instances
of of the popup menu.

Contents

Pages: 640

>>> popup = JPopupMenu("JFC Popup")


Characterized by ease of use, richness of expression, and concise syntax, Python has
Put some menu itemsremained
in it. a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
>>> fruits = the
("Apple",
"GrapeFruit",
"Grapes")
two languages,"Oranges",
when used in combination,
ideal for Web
and distributed enterprise
>>> for fruitapplication
in fruits:
development.

...

popup.add(fruit)

This tutorial begins with coverage of some of the basics of Python programming. Using
Create a frame, a pane,
andofa skill-building
label. The label
holds a and
string,
which shows
the state sessions,
of the current
popupwill
plenty
exercises
interactive
programming
this book
menuJFC.
help those new to programming develop an understanding of concepts and practical

>>>
>>>
>>>
>>>

techniques. For experienced programmers, the book demonstrates Python's breadth of

frame = JFrame(size=(200,200))
capabilities and shows the ways that Python interfaces with Java APIs for professional
pane = JPanel()
application development.
label = JLabel("JFC Popup Menu")
pop = JButton("Pop")
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web

and Enterprise Applications with Jython covers important topics such as:
Add the popup menu to the pane.

>>> pane.add(popup)
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
Add the label and pop components to the pane. Add the pane to the frame.
Python basics, including operators, string formatting, namespaces, classes, errors,

>>> pane.add(pop)
and exceptions
>>> pane.add(label)
>>> frame.contentPane.add(pane)
Object-oriented programming concepts

Create an event handler forFile


pop
that pops up the current menu at the x, y location20,10 in the pane.
input/output

>>> def popEvent(event):


Python's intrinsic functions
...
global popup, pane
...
popup.show(pane,
20, 10)
Formatting, parsing,
and manipulating strings
Register the event handlersInterfacing
with the corresponding
with the Javabuttons.
APIs and working with Java Streams

>>> pop.actionPerformed
popEvent
Using Python=and
Java Swing to create GUIs
Pack the frame, and show itWorking
off.
with SQL and JDBC(TM)

>>> frame.pack() Python and Java applets


>>> frame.visible=1
Putting Things
Together
with
Menubar
Menus
and Popup
Menusthe Python
In addition,
the book
contains
instructions
for downloading
and installing

Adding

language and the Java Development Kit (JDK). Terminology, definitions, explanations,
code samples
make this book a useful learning experience.
Menusand
tonumerous
the Address
Application

Whether you are a sophisticated computer user new to programming or a serious


Let's add a menubar application
menu and adeveloper,
popup menu
to ourProgramming
address application.
we'll set
the menubar
Python
with theEssentially,
Java(TM) Class
Libraries
will
property of AddressMain to a JMenuBar instance. Then we'll add the Address menu to the menubar and
give you insight into the power of Python and the know-how to put it to work.
give it two items, Add and Remove. The actionPerformed event properties of these items are set to the
same handler as for the Add and Remove buttons.

777

All of this is done from the constructor of AddressMain. It's rather long, so we'll break out the functionality
of adding the menu to a method called __init__menu(). Here's the code (from class AddressMain in

Two\AddressMain.py):
Python Programming

def

with the Java Class Libraries: A Tutorial for Building


Web and Enterprise Applications with Jython
__init__(self)
By Richard Hightower

...
self.__init__menu()
Publisher: Addison Wesley
...
Pub Date: June 28, 2002
def __init__menu(self):

Table of
Contents

ISBN: 0-201-61616-5

Pages: 640

# Create the JMenuBar and


# add it to the addressMenu.
Characterized by ease of use, richness of expression, and concise syntax, Python has
jmb = JMenuBar()
remained a premier programming language for more than a decade, and is used by
self.JMenuBar = JMenuBar
novices and professionals alike. In particular, its close relationship to Java(TM) makes
addressMenu = JMenu("Address")

the two languages, when used in combination, ideal for Web and distributed enterprise
application development.

# Create two menu items.


addAddress
= with
JMenuItem("Add")
This tutorial begins
coverage of some of the basics of Python programming. Using
removeAddress
JMenuItem("Remove")
plenty of skill-building=exercises
and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
# Add
the programmers,
menu items
to the
menu.Python's breadth of
techniques. For
experienced
the book
demonstrates
# then
add
menu interfaces
to thewith
menu
bar for professional
capabilities and
shows the
waysthe
that Python
Java APIs
addressMenu.add(addAddress)
application development.

addressMenu.add(removeAddress)
JMenuBar.add(addressMenu)
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

# Register the menu items event handler


addAddress.actionPerformed = self.__addAddress_Clicked
Fundamental programming concepts, including
statements, expressions,
removeAddress.actionPerformed=
self.__RemoveAddress_Clicked
interpreters, and compilers
We also want to add a popup menu to our application that appears when the user clicks the address list. The
Python
basics,toincluding
operators, ,string
formatting,
namespaces,
errors,
__init__popup method
is similar
__init__menu
the only
difference
being that classes,
the
and
exceptions
mousePressed event is handled for addresses. Notice that, if event.metaDown (in the event handler
for mousePressed) is true ( 1), the right mouse button was clicked.
Object-oriented programming concepts

def __init__(self)
File input/output
...
self.popup = NONEPython's#to
hold the popup menu
intrinsic functions
self.__init__popup()
self.addresses.mousePressed
self.__popupEvent
Formatting, parsing,=and
manipulating strings
...
Interfacing with the Java APIs and working with Java Streams

def __popupEvent(self, event):


Using Python and Java Swing
to create GUIs
if event.metaDown
== 1:
self.popup.show(self.addresses, event.x, event.y)
Working with SQL and JDBC(TM)

def __init__popup(self):
Python and Java applets
self.popup = JPopupMenu("Address")
Inself.addresses.add(self.popup)
addition, the book contains instructions for downloading and installing the Python
two menu
items.
language and#theCreate
Java Development
Kit (JDK).
Terminology, definitions, explanations,
addAddress
=
JMenuItem("Add")
and numerous code samples make this book a useful learning experience.
removeAddress = JMenuItem("Remove")
Whether you are a sophisticated computer user new to programming or a serious
# Add the
itemswith
tothethe
menu.
application developer,
Pythonmenu
Programming
Java(TM)
Class Libraries will
self.popup.add(addAddress)
give you insight into the power of Python and the know-how to put it to work.

self.popup.add(removeAddress)

777

# Register the menu item's event handler


addAddress.actionPerformed = self.__addAddress_Clicked

removeAddress.actionPerformed=
self.__RemoveAddress_Clicked
Python
Programming with the Java Class Libraries:
A Tutorial for Building
Web and Enterprise Applications with Jython
and
then remove
an address entry with the Add and Remove menu items on JMenuBar .
By Richard
Hightower

As an exercise, add
Do it again with JPopupMenu. Also create a duplicate menu item for both the menubar menu and the popup
menu that allows an address
to be Addison
duplicated,
that is, copied and pasted into the list.
Publisher:
Wesley
Pub Date: June 28, 2002
ISBN: 0-201-61616-5
Layout
Managers
Table of

Contents

Pages: 640

If you've worked with Visual Basic or any other tools that support GUI code generation, you may be accustomed
Characterized
ease
of use, richness
of and
expression,
concise
has The
1/20 inch.)
to laying out components
on a formbyand
specifying
their size
position and
in pixels.
(Asyntax,
pixel isPython
remained
a
premier
programming
language
for
more
than
a
decade,
and
is
used
by
problem is, of course, that you may develop your application on a 25-inch monitor, and then someone will try to
novices leaving
and professionals
alike.
its close
relationship
Java(TM)
makes
use it on a 12-inch monitor,
half the GUI
off In
theparticular,
screen. This
problem
becomes to
even
more pronounced
if
the
two
languages,
when
used
in
combination,
ideal
for
Web
and
distributed
enterprise
you have no control over the type of display your GUI will be used on. For these reasons, Java needs a flexible
applicationondevelopment.
way to display user interfaces
a variety of platforms.

This tutorial
with
coverage of
of thewith
basics
of Python
programming.
Using
Layout managers provide
a way tobegins
lay out
components
in asome
container
great
flexibility,
but with flexibility
plenty
of
skill-building
exercises
and
interactive
programming
sessions,
this
book
comes greater complexity, and sometimes there's just no substitute for absolute positioning. Even so, inwill
most
those
new to programming
develop
an understanding
of concepts
cases you should usehelp
layout
managers,
and if you do use
absolute
positioning, make
sure it'sand
in apractical
container whose
container is a layout techniques.
manager. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application on
development.
The positioning of components
the screen is decided by the order in which they're added to the container, the
constraints passed to the container's add() method, and the layout manager properties the container is using.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
andhas
Enterprise
Applications
Jython
covers
important
topics such as: and
Each type of container
its own default
layout with
manager.
For
example,
java.awt.Frame
javax.swing.JFrame use BorderLayout whereas Panel and JPanel use FlowLayout.
However, you can change the default so that a frame can use FlowLayout and a panel can use
Fundamental programming concepts, including statements, expressions,
BorderLayout.
interpreters, and compilers
In one GUI, you'll usually have many layout managers. Nested containers with different layout managers will
basics,
operators,
string formatting,
namespaces, classes,
errors,
give you the desired result,Python
as we saw
withincluding
the address
book application.
There AddressMain
used
and
exceptions
BorderLayout;ToolBar, which contains the Add and Remove buttons, used FlowLayout; and
editPane used GridLayout
(to arrange the labels and text fields used to edit the addresses).
Object-oriented programming concepts
The key to understanding layout
managers is using them, so we'll be doing plenty of interactive examples and
File input/output
exercises. I've also provided a tutor application (Layout3.py) that works with FlowLayout,
BorderLayout,GridLayout
, and GridBagLayout
. Feel free to fire up Layout3.py and experiment
Python's intrinsic
functions
with layout managers at any time.
Formatting, parsing, and manipulating strings

Interfacing with the Java APIs and working with Java Streams

Strategy Design Pattern

Using Python and Java Swing to create GUIs

The layout manager approach uses the Strategy design pattern developed by Gamma and his
Working with SQL and JDBC(TM)
colleagues (Design Patterns, 1995). This is another reminder to read Gamma, but first read ObjectOriented Analysis and
Design
(Booch, 1994).
Python
andwith
JavaApplications
applets

In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
TheFlowLayout class is the simplest of the layout managers. (Actually, it's the second simplest; I'll explain
later.) As components
are added
a time to the container,
they're
positioned
from leftortoaright
and from top
Whether
youone
are at
a sophisticated
computer user
new
to programming
serious
to bottom. When oneapplication
row fills up,
the components
begin filling upwith
the the
nextJava(TM)
row. YouClass
can set
the alignment
developer,
Python Programming
Libraries
will of
each row so that the give
components
caninto
be centered
or of
leftor right-aligned.
you insight
the power
Python
and the know-how to put it to work.

FlowLayout

Here's an interactive FlowLayout example. Import the FlowLayout class and some container and
component support classes.

777

>>> from java.awt


import FlowLayout
Python Programming
with the Java Class Libraries: A Tutorial for Building
>>> from javax.swing
import
JFrame,with
JButton,
JTextField, JLabel
Web and Enterprise
Applications
Jython
By Richard Hightower

Create an instance of Frame, and set its layout to FlowLayout, that is, an instance of the FlowLayout
class. Remember that the
frame is Addison
a container.
Publisher:
Wesley
Pub Date: June 28, 2002
>>> frame = JFrame("FlowLayout",
size = (200, 200), visible=1)
ISBN: 0-201-61616-5
>>> Table
frame.contentPane.layout
=
FlowLayout()
of

Contents

Pages: 640

Add a label to the frame, and validate the frame. (validate() forces the frame to redraw itself, which
makes the label just Characterized
added visible.)by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
>>> frame.contentPane.add(JLabel("Name"))
novices and professionals alike. In particular, its close relationship to Java(TM) makes
javax.swing.JLabel[...text=Name,...verticalTextPosition=CENTER]
the two languages, when used in combination, ideal for Web and distributed enterprise
>>> frame.validate()
application development.

This
tutorial
with
Add a text field to the
frame,
andbegins
validate
the coverage
frame. of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
>>> frame.contentPane.add(JTextField(20))
help those new to programming develop an understanding of concepts and practical
>>> frame.validate()
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
Remember, if the component
doesn't
fit on the current row, it's added to the next row. If we eyeball the
application
development.
components, they look like they almost fit. To be sure, we have to check their width.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
>>> frame.contentPane.components[0].width
+
and Enterprise Applications with Jython covers important
topics such as:

frame.contentPane.components[1].width
253

Fundamental programming concepts, including statements, expressions,


The first component's widthinterpreters,
( frame.contentPane.components[0]
) plus the second's width
and compilers
(frame.contentPane.components[1]) is 253. Take a look at the call to the constructor to see what
Python basics, including operators, string formatting, namespaces, classes, errors,
the frame width is.
and exceptions

>>> frame.width
200
Object-oriented programming concepts
File fit
input/output
Clearly both components can't
on the same row. (We'll make them fit later.)
Python's
intrinsic
Let's make this example more
interesting
andfunctions
add eight more components to the container (frame). Create a tuple
of strings and iterate through it, creating buttons with the strings and adding them to the frame.
Formatting, parsing, and manipulating strings

>>> blist = ("one", "two", "three", "four", "five", "six", "seven", "eight")
>>> for label in Interfacing
blist: with the Java APIs and working with Java Streams
...
frame.contentPane.add(Button(label))
Using Python and Java Swing to create GUIs
...
>>> frame.validate()
Working with SQL and JDBC(TM)

The frame should now look like Figure 14-7. Notice that the components in each row are centered, which is the
Python and Java applets
default row alignment with FlowLayout ( FlowLayout.CENTER). We'll change the alignment to the
left and then to the right.
Then we'll
change
the vertical
and horizontal
spacing between
the components.
In addition,
the book
contains
instructions
for downloading
and installing
the Python

language and the Java Development Kit (JDK). Terminology, definitions, explanations,
Figure
14-7.
Center
Alignment
of Components
( FlowLayout
's Default)
and
numerous
code
samples make
this book a useful
learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower
Publisher: Addison Wesley
Pub Date: June 28, 2002

Table of
Contents

ISBN: 0-201-61616-5
Pages: 640

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
twotolanguages,
Set the layout of the the
frame
the left. when used in combination, ideal for Web and distributed enterprise
application development.

>>> frame.contentPane.layout.alignment = FlowLayout.LEFT


This tutorial begins with coverage of some of the basics of Python programming. Using
>>> frame.contentPane.doLayout()
plenty of skill-building exercises and interactive programming sessions, this book will
help those
to programming
developare
analigned
understanding
of left
concepts
and
It should look like Figure
14-8.new
Notice
that the components
along the
border.
If practical
we change the
techniques.
For
experienced
programmers,
the
book
demonstrates
Python's
breadth of
layout to right alignment, the frame should look like Figure 14-9.
capabilities and shows the ways that Python interfaces with Java APIs for professional
application
development.
Figure
14-8.
Left Alignment of Components with FlowLayout
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
Object-oriented programming concepts
File input/output
Figure 14-9. Right Alignment of Components with FlowLayout
Python's intrinsic functions
Formatting, parsing, and manipulating strings
Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs
Working with SQL and JDBC(TM)
Python and Java applets
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book=a useful
learning experience.
>>> frame.contentPane.layout.alignment
FlowLayout.RIGHT

>>> frame.contentPane.doLayout()

Whether you are a sophisticated computer user new to programming or a serious


application
developer,
Python
with
the Java(TM)
Libraries
will bigger
Recall that the first two
components
didn't fit
on theProgramming
first row. What
would
happen ifClass
we made
the frame
give
you
insight
into
the
power
of
Python
and
the
know-how
to
put
it
to
work.
than the 253 pixels that make up the width of the label plus the width of the text field? Change the width of the
frame to 275 pixels.

777

>>> frame.size = 275, 200


>>> frame.contentPane.doLayout()

>>> frame.validate()
Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython

The frame should now


look likeHightower
Figure 14-10.
By Richard
Figure 14-10.
Effect
of
Publisher:
Addison
Wesley

Resizing on Component Layout

Pub Date: June 28, 2002

Table of
Contents

ISBN: 0-201-61616-5
Pages: 640

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
Let's set the spacing between the components with the vgap property, which controls vertical spacing, and the
capabilities and shows the ways that Python interfaces with Java APIs for professional
hgap property, which controls horizontal spacing. Set vgap and hgap to 0 so that your frame will look like
application development.
the one in Figure 14-11.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
Figure 14-11.
Vertical
Horizontal
Gap Set
to 0such as:
and Enterprise
Applications
withand
Jython
covers important
topics
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
Object-oriented programming concepts
File input/output
Python's intrinsic functions
Formatting, parsing, and manipulating strings

>>> frame.contentPane.layout.vgap=0
>>> frame.contentPane.layout.hgap=0
Interfacing with the Java APIs and working with Java Streams
>>> frame.contentPane.doLayout()
Using Python and Java Swing to create GUIs
Now set vgap and hgap to 10 pixels.
Working with SQL and JDBC(TM)

>>> frame.contentPane.layout.vgap=10
>>> frame.contentPane.layout.hgap=10
Python and Java applets
>>> frame.contentPane.doLayout()
In addition, the book contains instructions for downloading and installing the Python
Finally, we want to pack
the frame
with
FlowLayout
if the
container
is an instance
of JFrame
,
language
and the
Java
Development Kit
(JDK).
Terminology,
definitions,
explanations,
JDialog, or Window
.FlowLayout
lays out
the components'
preferredSize
property (if you try to
and numerous
code samples
make
this book a useful
learning experience.
resize a component yourself, FlowLayout will change it back) and adjusts the width of the frame to the
you are a sophisticated
user
new to programming
or a serious will try
cumulative width of Whether
all of its components.
If you packcomputer
the frame
(frame.pack()
),FlowLayout
application
developer,
Programming
to fit all of the components
on the
top row, Python
as in Figure
14-12. with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.
Figure 14-12. Result of Packing the Frame

777

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

Surprise

Publisher: Addison Wesley


Pub Date: June 28, 2002

All of you who weren't following along (and you know who you are), fire up layout4.py, which lets you adjust
ISBN: 0-201-61616-5
properties
Tablefor
of all of the layout managers that we discuss in this chapter. It looks like Figure 14-13. Notice, in the

Pages: 640
frame Contents
at the left, that you can adjust the properties of the current layout and those of the components (or those of
theconstraint objects associated with a component). Play around with it:
Characterized by ease of use, richness of expression, and concise syntax, Python has
a premier
programming
language for more than a decade, and is used by
1. Set the layout remained
manager to
FlowLayout
.
novices
and
professionals
alike.
In
relationship
Java(TM)
makesthe
2. Align the components on the left by selecting theparticular,
LEFT itemitsinclose
the alignment
listtoand
then clicking
the
two
languages,
when
used
in
combination,
ideal
for
Web
and
distributed
enterprise
Apply button.
application
development.
3. Align the components
on the
right.
4.
5.
6.
7.
8.
9.
10.

Change the vertical gap to 0 by editing the vgap text field to 0 and then hitting the Apply button.
This tutorial begins with coverage of some of the basics of Python programming. Using
Change the horizontal gap to 0.
plenty of skill-building exercises and interactive programming sessions, this book will
Change the vertical and horizontal gaps to 20.
help those new to programming develop an understanding of concepts and practical
Size the frame with the mouse so that it's half its original size.
techniques. For experienced programmers, the book demonstrates Python's breadth of
Hit the Resize button on the control frame.
capabilities and shows the ways that Python interfaces with Java APIs for professional
Hit the Pack button to resize the frame.
application development.
Try all of the available layout managers.

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
Figure
14-13. Layout4.py
Playing
with
It such as:
and Enterprise
Applications
with Jythonafter
covers
important
topics
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
Object-oriented programming concepts
File input/output
Python's intrinsic functions
Formatting, parsing, and manipulating strings
Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs
Working with SQL and JDBC(TM)
Python and Java applets
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.
There are four versions of the layout program, Layout.py,Layout2.py,Layout3.py, and Layout4.py, which
increase in complexity. To understand what's going on, examine Layout.py without looking at Layout4.py,
which, since it supports all of the layout managers, is pretty long.

777

BoxLayout

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
Richard
Hightower
You may remember By
that
I referred
to FlowLayout as the second simplest layout manager. It used to be the

easiest, but that was before BoxLayout, which was added as part of JFC/Swing. BoxLayout can be used
Addison
with AWT components,Publisher:
but it works
betterWesley
with the JFC variety.
Pub Date: June 28, 2002

BoxLayout has only oneISBN:


parameter,
AXIS, and there are only two choices: X and Y. Here's a short
0-201-61616-5
Table of
interactive
example.

Contents

Pages: 640

ImportBoxLayout
,JFrame, and
javax.swing.
Characterized
byJButton
ease of use,from
richness
of expression, and concise syntax, Python has

remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two
languages,
Create a frame, and add
some
buttons towhen
it. used in combination, ideal for Web and distributed enterprise
application development.

>>> from javax.swing import BoxLayout, JFrame, JButton

>>> frame = JFrame("BoxLayout Example", size = (300,200), visible=1)


This tutorial begins with coverage"four"]
of some of the basics of Python programming. Using
>>> list = ["one","two","three",
plenty
of
skill-building
exercises
and
interactive programming sessions, this book will
>>> for button in list:
help
those
new
to
programming
develop
an understanding of concepts and practical
...
frame.contentPane.add(JButton(button))
techniques.
For
experienced
programmers,
the book demonstrates Python's breadth of
...
capabilities and shows the ways that Python interfaces with Java APIs for professional
development.
Change the layout ofapplication
the frame to
BoxLayout, which uses X_AXIS. (invalidate() tells the frame that
something has changed and that the window needs to be redrawn; validate() tells the frame that it's time to
Python
Programming withand
the then
Java(TM)
Class Libraries:
Tutorial
forcall
Building
Web .)
fix any problems. Calling
invalidate()
validate()
forcesAthe
frame to
doLayout
and Enterprise Applications with Jython covers important topics such as:

>>> frame.contentPane.layout=BoxLayout(frame.contentPane, BoxLayout.X_AXIS)


>>> frame.invalidate()
Fundamental programming concepts, including statements, expressions,
>>> frame.validate()
interpreters, and compilers

Look at Figure 14-14, and notice that BoxLayout has arranged things from left to right along the x axis. Now
Python basics, including operators, string formatting, namespaces, classes, errors,
arrange the layout along the y axis (Figure 14-15).
and exceptions
FigureObject-oriented
14-14. Components
Laid concepts
Out Left to Right on the x Axis
programming

File input/output
Python's intrinsic functions
Formatting, parsing, and manipulating strings
Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs
Working with SQL and JDBC(TM)
Python and Java applets
InFigure
addition,
the book
contains instructions
downloading
and yinstalling
14-15.
Components
Laid Outfor
Vertically
on the
Axis the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower
Publisher: Addison Wesley
Pub Date: June 28, 2002

Table of
Contents

ISBN: 0-201-61616-5
Pages: 640

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributedBoxLayout.Y_AXIS)
enterprise
>>> frame.contentPane.layout=BoxLayout(frame.contentPane,
application
development.
>>> frame.invalidate()

>>> frame.validate()

This tutorial begins with coverage of some of the basics of Python programming. Using
of skill-building
exercises
and interactiveproperty.
programming
sessions,
will
LikeFlowLayoutplenty
,BoxLayout
uses the
preferredSize
It simply
spacesthis
thebook
components
help
those
new
to
programming
develop
an
understanding
of
concepts
and
practical
evenly against a given axis. Try this exercise using BoxLayout from Layout4.py. Explain what happens in
techniques. For experienced programmers, the book demonstrates Python's breadth of
each step.
capabilities and shows the ways that Python interfaces with Java APIs for professional
development.to hit the Apply button on the control frame.)
1. Set the axis toapplication
X_AXIS. (Remember
2. Reduce the size of the frame to half and then half again along the x axis.
the Java(TM) Class Libraries: A Tutorial for Building Web
3. Hit the ResizePython
button Programming
on the control with
frame.
and
Enterprise
Applications
with is
Jython
covers
important
topics such as: .)
4. Hit the Pack button on the control frame. (This
the same
as calling
frame.pack()
5. Set the axis to Y_AXIS.
6. Hit the Resize buttonFundamental
again to set the
frame to the
default starting
size.
programming
concepts,
including
statements, expressions,
7. Reduce the size of the
layout
frame
by
half
and
then
by
half
again
along
the y axis.
interpreters, and compilers
8. Hit the Pack button again.
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
GridLayout
Object-oriented
programming
concepts
TheGridLayout manager
lays out components
in a grid.
We used it in the address application for
editPane . Like FlowLayout,GridLayout has the vgap and hgap properties that set the vertical
File input/output
and horizontal spacing between components.
Python's intrinsic functions

GridLayout also has properties that specify the rows and columns of the grid. The row property is dominant.
The only component property
that GridLayout
any attention
to is minimumSize. If you pack the
Formatting,
parsing, and pays
manipulating
strings
container (frame.pack()), it uses minimumSize to create the smallest components that are all the same
size. It ignores preferredSize
width
heightwith
of the
components
Interfacingand
withstretches
the Javathe
APIs
andand
working
Java
Streams so that they all have
the same area and fill the container (if possible). Here's an example.
Using Python and Java Swing to create GUIs
Import the classes needed.
Working with SQL and JDBC(TM)

>>> from java.awt import GridLayout


Python and
Java applets
>>> from javax.swing
import
JFrame, JButton
In addition,
the book contains
Create a frame and add
some components
to it. instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
>>> frame = JFrame("GridLayout
Example",
size=(300,300),
and numerous code samples make
this book a useful
learning experience. visible=1)

>>> blist = ("One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight")
you are a sophisticated computer user new to programming or a serious
>>> for labelWhether
in blist:
application developer, Python Programming with the Java(TM) Class Libraries will
...
frame.contentPane.add(JButton(label))
give you insight into the power of Python and the know-how to put it to work.
...
Create a grid layout that lays out components in a 2-by-4 grid.

777

>>> frame.contentPane.layout = GridLayout(2,4)

>>> frame.contentPane.doLayout()
Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython

Your frame should look


like Figure
14-16. Notice that neither the width nor the height is observed from
By Richard
Hightower
preferredSize. With the mouse, drag the right corner of the frame so that it's twice its original size, which
doubles the width and height
of theAddison
components
as well. Now return the frame to its original size.
Publisher:
Wesley
Pub Date: June 28, 2002

Figure 14-16. A 2-by-4 Component Layout with GridLayout

Table of
Contents

ISBN: 0-201-61616-5

Pages: 640

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
Fundamental programming concepts, including statements, expressions,
Set the row property of theinterpreters,
GridLayout
instance to 3.
and compilers

>>> frame.contentPane.layout.rows=3
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
Your frame should now look like Figure 14-17. Although we didn't change the columns to 3, only three columns
show up. That's because GridLayout
the number
of columns to fit the desired number of rows. Also,
Object-orientedadjusts
programming
concepts
the grid is 3 by 3 and, since we only have eight components, the last cell is left blank.
File input/output
Figure 14-17. A 3-by-3 Layout (with the Last Cell Blank)
Python's intrinsic functions
Formatting, parsing, and manipulating strings
Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs
Working with SQL and JDBC(TM)
Python and Java applets
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Now set the rows to four. Then print out the row and column properties (layout.rows and
layout.columns).

>>>
>>>
>>>
>>>
4 4

Python Programming with the Java Class Libraries: A Tutorial for Building
frame.contentPane.layout.rows=4
Web and Enterprise Applications with Jython
frame.contentPane.doLayout()
By Richard Hightower
layout=frame.contentPane.layout
print layout.rows, layout.columns
Publisher: Addison Wesley
Pub Date: June 28, 2002

0-201-61616-5
Your frame should look likeISBN:
Figure
14-18. Again, the number of columns has changed to accommodate the
Table of

Pages:
640 property is still set to 4 because, as I said earlier, the row property is
number
of
rows;
however,
the
column
Contents
dominant.
Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premierFigure
programming
more than a decade, and is used by
14-18.language
A 4-Rowfor
Layout
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.

This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
Setvgap and hgap of frame.layout
to 3. Look atconcepts
the frame, and then set these properties to 7.
Object-oriented programming

>>> layout.vgap, File


layout.hgap
= 3,3
input/output
>>> frame.contentPane.doLayout()
Python's intrinsic functions
Look at the frame.

Formatting, parsing, and manipulating strings

>>> layout.vgap, layout.hgap = 7,7


>>> frame.invalidate();frame.validate()
Interfacing with the Java APIs and working with Java Streams
It should look like Figure 14-19.
the components and not between the
Using Notice
Python that
and the
Javaspacing
Swing istobetween
create GUIs
components and the edges. (If you want to set the area between the components and the edges, you need to set
theinsets of the frame.)Working with SQL and JDBC(TM)

Python
Java Horizontal
applets
Figureand
14-19.
and Vertical Gap Set to 3
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower
Publisher: Addison Wesley
Pub Date: June 28, 2002

Table of
Contents

ISBN: 0-201-61616-5
Pages: 640

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
Set the layout back totechniques.
the way it For
was.experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application
development. = 0,0
>>> layout.vgap,
layout.hgap

>>> frame.contentPane.layout = GridLayout(2,4)

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterpriseuses
Applications
with Jython
covers
topics It
such
As we discussed, GridLayout
minimumSize
when
youimportant
pack the frame.
laysas:
out all components
with the same size by checking the minimum size for each one and then setting all of them to the largest size it
finds. Pack the frame. It should look like Figure 14-20.
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
Figure 14-20. Packed Frame
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
Object-oriented programming concepts
File input/output

>>> frame.pack() Python's intrinsic functions


Formatting,and
parsing,
andmaximum
manipulating
strings
Now let's go through the components
find the
minimumSize
. First we'll create two lists to
collect the widths and heights from the components.
Interfacing with the Java APIs and working with Java Streams

>>> widths, heights = [], []

Using Python and Java Swing to create GUIs

Iterate through the components in the frame, and collect the widths and heights in the widths and heights lists.
Working with SQL and JDBC(TM)

>>> for component in frame.contentPane.components


Python and Java applets
...
widths.append(component.minimumSize.width)
...
heights.append(component.minimumSize.height)
In addition, the book contains instructions for downloading and installing the Python
language and the Java
Development Kit (JDK). Terminology, definitions, explanations,
Print the maximum minimumSize
width.
and numerous code samples make this book a useful learning experience.

>>> print "Minimum width " + `max(widths)`


Minimum widthWhether
48 you are a sophisticated computer user new to programming or a serious

application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into
the power of Python and the know-how to put it to work.
Print the maximum minimumSize
height.

>>> print "Minimum height " + `max(heights)`


Minimum height 23

777

Print the actual size of


the components.
(Remember
that
with GridLayout
components
the same
Python
Programming
with the
Java
Class Libraries:all
A Tutorial
for are
Building
size.) Notice that theWeb
widthand
andEnterprise
height match
the maximum
minimumSize
.
Applications
with
Jython
By Richard Hightower

>>> print "Size of all of the components " + `frame.components[0].size`


Size of all of Publisher:
the components
java.awt.Dimension[width=48,height=23]
Addison Wesley
Pub Date: June 28, 2002

Try this exercise with layout4.py:


1.

ISBN: 0-201-61616-5
Table of
Pages:
SelectGridLayout from640
the layouts list in the
Contents

control pane.
2. Hit the Pack button. You should have a frame that looks like Figure 14-21.
Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier
programming
language
for more thanFrame
a decade, and is used by
Figure
14-21. Packed
GridLayout
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.

This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
Programming
thehit
Java(TM)
Class
Libraries:
A Tutorial
Web143. ChangehgapPython
and vgap
to 5 pixels.with
Then
the Apply
button.
The frame
should for
lookBuilding
like Figure
and
Enterprise
Applications
with
Jython
covers
important
topics
such
as:
22.
Figure
14-22.programming
Frame with concepts,
Horizontal
and Vertical
Gaps
of 5
Fundamental
including
statements,
expressions,
interpreters, and compilers

Python basics, including operators, string formatting, namespaces, classes, errors,


and exceptions
Object-oriented programming concepts
File input/output
Python's intrinsic functions
4.
5.
6.
7.
8.

Formatting, parsing, and manipulating strings


Hit the Pack button again.
Change the number Interfacing
of columns with
to 100.
happens?
theWhat
Java APIs
and working with Java Streams
Set the number of columns to 0. What happens?
Set the number of columns
back toand
5. What
happens?
Using Python
Java Swing
to create GUIs
Set the rows from 4 to 6. Then hit Pack. Notice that the last two rows are empty (Figure 14-23).
Working with SQL and JDBC(TM)
Figure 14-23. Six-Row Packed Frame with Last Two Rows Empty
Python and Java applets
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

9. Increment the rows by 1 until you reach 10. Be sure to hit Apply each time, and then repack the frame
with Pack.

9.
Python Programming with the Java Class Libraries: A Tutorial for Building

BorderLayoutWeb and Enterprise Applications with Jython


By Richard Hightower

BorderLayout works well with top-level containers. It can have at most five components, so the
Wesley
components added to itPublisher:
are usuallyAddison
containers
themselvesthat is, panels.
Pub Date: June 28, 2002

The five regions of BorderLayout


are north, south, east, west, and center. What you put in them is up to
ISBN: 0-201-61616-5
Table of
you and is application-specific.
North
Pages:
640is used mainly for toolbars (panels with buttons or similar components);
Contents
south, usually for status windows (panels with labels that show the status of an application). West can be used
for tree views, lists, and
the like; east,
for toolboxes
(panelsofwith
buttons and
text fields).
Center
Characterized
by ease
of use, richness
expression,
and property
concise syntax,
Python
has is
usually the main view
of the application,
perhaps wherelanguage
the text for
fields
forthan
editing
an object
located.
remained
a premier programming
more
a decade,
andare
is used
by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
The north and south the
regions
span the fullwhen
width
of the
parent container.
height
the preferred
height of the
two languages,
used
in combination,
idealTheir
for Web
andisdistributed
enterprise
component. The eastapplication
and west regions
span the full height of the container minus the height of the north and/or
development.
south regions (if any). Their width is the preferred width of the component. The center region gets whatever is
left over, usually theThis
largest
portion
of the
frame.
Now for
our BorderLayout
example.
tutorial
begins
with
coverage
of some
of the basics of Python
programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
Set up a frame.
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
>>> from java.awt
import BorderLayout
capabilities and shows the ways that Python interfaces with Java APIs for professional
>>> from javax.swing
import JFrame, JButton
application development.

>>> f = JFrame("BorderLayout", size = (300,300), visible=1)


>>> f.contentPane.layout
BorderLayout()
Python Programming=with
the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
Add a button to the north region, and force the frame to lay out the components (Figure 14-24).
Figure 14-24.
BorderLayout
Frame
with including
a Buttonstatements,
in the North
Region
Fundamental
programming
concepts,
expressions,
interpreters, and compilers

Python basics, including operators, string formatting, namespaces, classes, errors,


and exceptions
Object-oriented programming concepts
File input/output
Python's intrinsic functions
Formatting, parsing, and manipulating strings
Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs
Working with SQL and JDBC(TM)
Python and Java applets
In addition, the book contains instructions for downloading and installing the Python
>>> f.contentPane.add(JButton("NORTH"),BorderLayout.NORTH)
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
>>> f.contentPane.doLayout()
and numerous code samples make this book a useful learning experience.

Notice that the button's width is stretched to the full width of the container. Add a button to the east region
Whether you are a sophisticated computer user new to programming or a serious
(Figure 14-25).
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.
Figure 14-25. BorderLayout Frame with a Button Added in the East Region

777

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower
Publisher: Addison Wesley
Pub Date: June 28, 2002

Table of
Contents

ISBN: 0-201-61616-5
Pages: 640

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the
book demonstrates Python's breadth of
>>> f.contentPane.add(JButton("EAST"),
BorderLayout.EAST)
capabilities
and
shows
the
ways
that
Python
interfaces
with Java APIs for professional
>>> f.contentPane.doLayout()
application development.
Notice that its height is the full height of the container minus the height of the button added to the north region.
Python
Programming
with the Java(TM) Class Libraries: A Tutorial for Building Web
Add a button to the west
region
(Figure 14-26).
and Enterprise Applications with Jython covers important topics such as:
Figure 14-26. BorderLayout Frame with a Button Added in the West Region

Fundamental programming concepts, including statements, expressions,


interpreters, and compilers
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
Object-oriented programming concepts
File input/output
Python's intrinsic functions
Formatting, parsing, and manipulating strings
Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs
Working with SQL and JDBC(TM)
Python and Java applets

>>> f.contentPane.add(JButton("WEST"), BorderLayout.WEST)


In addition, the book contains instructions for downloading and installing the Python
>>> f.contentPane.doLayout()
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous
code samples
Add a button to the south
region (Figure
14-27). make this book a useful learning experience.
Whether
you are a sophisticated
user newAdded
to programming
or a serious
Figure 14-27.
BorderLayout
Framecomputer
with a Button
in the South
Region
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower
Publisher: Addison Wesley
Pub Date: June 28, 2002

Table of
Contents

ISBN: 0-201-61616-5
Pages: 640

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, theBorderLayout.SOUTH)
book demonstrates Python's breadth of
>>> f.contentPane.add(JButton("SOUTH"),
capabilities
and
shows
the
ways
that
Python
interfaces
with Java APIs for professional
>>> f.contentPane.doLayout()
application development.
Notice that the height of the west and south buttons decreases by the height of the south button. Add a button to
Python
Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
the center region (Figure
14-28).
and Enterprise Applications with Jython covers important topics such as:
Figure 14-28. BorderLayout Frame with a Button Added in the Center Region

Fundamental programming concepts, including statements, expressions,


interpreters, and compilers
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
Object-oriented programming concepts
File input/output
Python's intrinsic functions
Formatting, parsing, and manipulating strings
Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs
Working with SQL and JDBC(TM)
Python and Java applets

>>> f.contentPane.add(JButton("CENTER"), BorderLayout.CENTER)


In addition, the book contains instructions for downloading and installing the Python
>>> f.contentPane.doLayout()
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
Notice that it gets alland
thenumerous
leftovers. code samples make this book a useful learning experience.
Whether
youeast
are and
a sophisticated
user
to programming
a serious added to
Let's verify that the width
of the
west regionscomputer
is equal to
thenew
preferred
size of the or
components
application
developer,
Python Programming
with the Java(TM) Class Libraries will
them. Set up some constants
to extract
the components
from the container.
give you insight into the power of Python and the know-how to put it to work.

>>> NORTH,EAST,WEST,south=0,1,2,3

777

Get the preferred size and the actual size of the component added to the east region.

>>> f.contentPane.components[EAST].preferredSize

java.awt.Dimension[width=65,height=27]
Python Programming with the Java Class Libraries: A Tutorial for Building
>>> f.contentPane.components[EAST].size
Web and Enterprise Applications with Jython
java.awt.Dimension[width=65,height=219]
By Richard Hightower
Get the preferred size and
the actual
size ofWesley
the component added to the west region.
Publisher:
Addison
Pub Date: June 28, 2002
>>> f.contentPane.components[WEST].preferredSize
ISBN: 0-201-61616-5
java.awt.Dimension[width=69,height=27]
Table of

Pages:
640
>>> Contents
f.contentPane.components[WEST].size
java.awt.Dimension[width=69,height=219]

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained
premier
programming
moretothan
decade,
used65.
byAlso
Notice that the preferred
widthaand
the actual
width of language
the buttonfor
added
the aeast
regionand
areisboth
novices
and
professionals
alike.
In
particular,
its
close
relationship
to
Java(TM)
makes
notice that the preferred width and the actual width of the button added to the west region are both 69.
the two languages, when used in combination, ideal for Web and distributed enterprise
application
development.
As an exercise, use the
same technique
just demonstrated to prove that the north and south regions stretch the
width of the component but use the preferred height. Then, using Layout4.py, try this:
This tutorial begins with coverage of some of the basics of Python programming. Using
1. Change the layout
manager
in the layouts
list toand
BorderLayout
.
plenty
of skill-building
exercises
interactive programming
sessions, this book will
help
those newintothe
programming
an understanding of concepts and practical
2. Select the north
component
components develop
list.
techniques.
experienced
programmers,
thesets
book
Python's
of was
3. Select height in
the growthFor
direction
list. The
Grow button
thedemonstrates
preferred height
of thebreadth
button that
capabilities
and
shows
the
ways
that
Python
interfaces
with
Java
APIs
for
professional
added to the north region.
development.
4. Hit the Grow application
button several
times to make the north region expand.
5. Make the frame half the width and height it was before. Do this in small increments with the mouse.
with the Java(TM)
Class Libraries: A Tutorial for Building Web
Notice that thePython
heightProgramming
of the north component
doesn't change.
and
Enterprise
Applications
with
Jython
covers
important topics such as:
6. Hit the Resize button to set the size back to normal.
7. Make the frame twice as big (use the mouse to drag the corner of the frame). Notice that the north
component doesn't change.
Fundamental programming concepts, including statements, expressions,
8. Hit the Resize button.
interpreters, and compilers
9. Select the west component in the components list.
10. Select the width itemPython
in the basics,
growthincluding
direction list.
operators, string formatting, namespaces, classes, errors,
11. Hit the Grow buttonand
several
times.
Notice
that the width of the west button grows.
exceptions
12. Make the frame larger and smaller by dragging a corner.
13. Change the horizontal
and vertical gap
properties toconcepts
5, and hit the Apply button.
Object-oriented
programming
If you've followed along the
layout
frame should look like Figure 14-29.
File
input/output

Python's intrinsic
Figurefunctions
14-29. Layout4.py Result
Formatting, parsing, and manipulating strings
Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs
Working with SQL and JDBC(TM)
Python and Java applets
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

GridBagLayout

777

GridBagLayout is the most complex and most feared layout manager. It's also the most hated and yet the

most loved. Most important,


it's the most powerful
and,Java
in my Class
opinion,
the most Auseful.
Python Programming
with the
Libraries:
Tutorial for Building
Web and Enterprise Applications with Jython

This layout managerBy


is Richard
somewhat
like GridLayout in that you lay out components in cells in a grid.
Hightower
However, its components can span multiple cells, and the cells aren't always the same size. Instead, you set the
ratio of container spacePublisher:
the cells will
use. For
example, one column of cells can span half the width of the
Addison
Wesley
container; the other twoPub
columns
can span a quarter of the width.
Date: June 28, 2002
0-201-61616-5
UnlikeTable
in GridLayout
, ISBN:
in GridBagLayout
components don't have to span the width and height of the
of

Pages: 640
cells, so
their preferred size can be maintained. You can specify that the component width and/or height span the
Contents
cell width or height. You can also specify that the component be anchored in the center, north, south, east, or
west region of a cell.Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
GridBagConstraints
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
To create a GridBagLayout component, you need to master the GridBagConstraints class, which
specifies all constraints
a given
cell. The
class
are basics
associated
with components
added
to the
Thisfor
tutorial
begins
withinstances
coverageof
ofthis
some
of the
of Python
programming.
Using
container that has GridBagLayout
as
its
layout
manager.
GridBagConstraints
determines
the
plenty of skill-building exercises and interactive programming sessions, this book will
placement, cell dimensions,
alignment,
ratio, and so forth.
Theanassociation
among
the GridBagLayout
help those
new to programming
develop
understanding
of concepts
and practical
instance, GridBagConstraints
,
and
each
component
defines
the
overall
layout
of components
techniques. For experienced programmers, the book demonstrates Python's
breadthinofthe
container.
capabilities and shows the ways that Python interfaces with Java APIs for professional

application development.
Here are GridBagConstraint's properties:
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
andEnterprise
Applications
Jython
covers important topics such as:
gridx,gridy
defines the
cell locationwith
of the
constraint

gridheight,gridwidth defines the cell width and cell height

Fundamental programming concepts, including statements, expressions,


interpreters,
weightx,weighty
definesand
thecompilers
ratio between the cells
basics, including
operators,
stringtheformatting,
namespaces,
anchor defines Python
the justification
of a component
within
cell (CENTER
,NORTHclasses,
,WEST, errors,
etc.)
and exceptions
fill holds the fill type, i.e., whether or not the component spans the width or height of the cell
Object-oriented
programming
concepts
(possible values are BOTH
,VERTICAL
,NONE,HORIZONTAL
)
input/output
insets sets theFile
insets
Python's
intrinsic
functions
ipadx,ipady sets
additional
padding
needed for a cell (width or height in addition to the ratio
defined by weightx or weighty for a particular cell)
Formatting, parsing, and manipulating strings

The number of rows and columns in the container is a function of the largest gridx and gridy specified in a
Interfacing with the Java APIs and working with Java Streams
constraint if no rows or columns are blank. Say you specify a particular cell location as gridx=5,gridy=5.
If there are no cells in the fourth
or column
butSwing
there to
arecreate
cells GUIs
in the third row or column, cell 5,5 actually
Using row
Python
and Java
equates to cell 4,4.
Working with SQL and JDBC(TM)
GridBagLayout lays out cells left to right and then top to bottom, so gridx=0 and gridy=0,
respectively, indicate the first
row and Java
first column
Python
applets at the top left corner of the component.

gridheight andIngridwidth
specify
the cellinstructions
width. If we
a constraint
has a gridx
and a
addition, the book
contains
forhave
downloading
andthat
installing
the Python
gridy of 1 and a gridheight
a gridwidth
of 2,
that region
spans multiple
cells explanations,
(1,1 to 3,3).
language and theand
Java
Development Kit
(JDK).
Terminology,
definitions,
and numerous code samples make this book a useful learning experience.

weightx and weighty specify the ratio given to a certain cell. If the weightx is 0, there's another cell in
the same column setting
the ratio
space for it.
If weighty
is 0,tothere's
another cell
that row setting
Whether
you of
arewidth
a sophisticated
computer
user new
programming
or a in
serious
the ratio of height space
for
the
column.
If
three
cells
in
the
row
have
weightx
of
33,
each
cell
getswill
a
application developer, Python Programming with the Java(TM) Class Libraries
horizontal width equal
to you
33 percent
width
of of
thePython
container,
words, to
each
give
insight of
intothe
the
power
and in
theother
know-how
putcell
it towidth
work.=
33/(33+33+33) = 33%.

777

If three cells in the same column have a weight of 33, each cell gets a vertical height equal to 33 percent of the
height of the container, in other words, each cell height = 33/(33+33+33) = 33%.

fill holds the fill Python


type. TheProgramming
possible valueswith
in this
situation
BOTH
,VERTICAL
,NONE
, and
the
Java are
Class
Libraries:
A Tutorial
for
Building
HORIZONTAL.BOTH
specifies
that the component
spanwith
bothJython
the vertical and horizontal space of the cell (this
Web
and Enterprise
Applications
is similar to the GridLayout
cells). VERTICAL specifies that the component stretch across the vertical area
By Richard Hightower
of the cell. HORIZONTAL specifies that the component stretch across the horizontal area of the cell. NONE
specifies that the component
not stretch
in Wesley
either direction, so that it remains its preferred size in the cell.
Publisher:
Addison
Pub Date: June 28, 2002
ISBN:
0-201-61616-5
A GridBagLayout
Example
Table of

Contents

Pages: 640

Theory is good, but we need to put some code behind these abstract concepts. The following example, from
Characterized by ease of use, richness of expression, and concise syntax, Python has
GridBag.py, takes us step by step through the layout of components with GridBagLayout. At first we'll use
remained a premier programming language for more than a decade, and is used by
only buttons; then we'll graduate to other components such as text fields and labels. To start, import the classes
novices and professionals alike. In particular, its close relationship to Java(TM) makes
needed.
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
>>> from javax.swing
import JButton, JTextField, JFrame, JButton, JPanel, JLa

>>> from java.awt import GridBagLayout, GridBagConstraints

This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
Constraints help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
Define a helper function
for creating
GridBagConstraints
. If you'rewith
following
along
the interactive
capabilities
and shows
the ways that Python interfaces
Java APIs
forinprofessional
interpreter, enter from
GridBag
import
makeConstraint
.
application development.

def makeConstraint()
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
gridx=0, gridy=0,
# Holdswith
the
x, covers
y cell
location
and Enterprise Applications
Jython
important
topics suchin
as: the grid
gridheight=1, gridwidth=1, # Holds the cell width and cell height
weightx=0,weighty=0,
# Determines ratio relative to another.
Fundamental programming concepts,
including
statements,
expressions,
anchor= GridBagConstraints.CENTER,
# Holds
the
justification
interpreters, and compilers # Holds the fill type BOTH, NONE,...
fill=GridBagConstraints.NONE,
insets=Insets(0,0,0,0),
Python basics, including operators, string formatting, namespaces, classes, errors,
ipadx=0, ipady=0
):
and exceptions
return
GridBagConstraints(gridx,gridy,gridwidth,gridheight,weightx,weighty,anchor,
Object-oriented programming concepts
fill,insets, ipadx, ipady)
File input/output
Import the helper method to create GridBagConstraints without specifying all of its parameters.
Python's intrinsic functions

>>> from GridBag import makeConstraint

Formatting, parsing, and manipulating strings


Create a GridBagLayout instance. Then create a panel that has its layout manager property set to the
GridBagLayout instance.
Interfacing with the Java APIs and working with Java Streams

>>> gbag = GridBagLayout()


Using Python and Java Swing to create GUIs
>>> contentPane = JPanel(layout=gbag)
>>> frame = JFrame(contentPane=contentPane)
Working with SQL and JDBC(TM)
Python
andfirst
Javadefining
applets the top left region.
Create a 2-rowby2-column
layout,

>>> top_left In=addition,


makeConstraint(0,0,1,1,
weightx=20,
the book contains instructions for
downloading andweighty=50,
installing the Python
fill=GridBagConstraints.BOTH)
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Notice that gridx and gridy are both set to 0, so this component will be in the top left, or the first row, first
column of the grid. Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
Define the top right region.
give you insight into the power of Python and the know-how to put it to work.

>>> top_right = makeConstraint(1,0,1,1, weightx=80,


fill=GridBagConstraints.BOTH)

777

Notice that gridx is set to 1 and gridy is set to 0, which means that this region equates to the cell located at

the first row, secondPython


column Programming
of the grid.
Define the bottom

with the Java Class Libraries: A Tutorial for Building


Web and Enterprise Applications with Jython
left
Byregion.
Richard Hightower

>>> bottom_left = makeConstraint(0,1,1,1, weighty=50,


Publisher: Addison Wesley
fill=GridBagConstraints.BOTH)
Pub Date: June 28, 2002

0-201-61616-5
gridx
is set to 0, so this isISBN:
the first
column. gridy is set to 1, so this is the second row.
Table of

Contents

Pages: 640

>>> bottom_right = makeConstraint(1,1,1,1,fill=GridBagConstraints.BOTH)


Characterized by ease of use, richness of expression, and concise syntax, Python has
Notice that weightx
of cell atop_left
(0,0) is setlanguage
to 20 andfor
weightx
cell top_right
remained
premier programming
more thanofa decade,
and is used (1,0)
by is set to
80. This means that the
top left
will get 20/(20+80),
or 20 percent,
of the
width of the
container and
that the
novices
andcell
professionals
alike. In particular,
its close
relationship
to Java(TM)
makes
top right cell will getthe
80/(20+80),
or 80 when
percent,
of in
thecombination,
width. Also notice
thatWeb
bothand
cells,
top_left
and
two languages,
used
ideal for
distributed
enterprise
top_right, haveapplication
weightydevelopment.
of 50, so each gets 50/(50+50), or 50 percent, of the height of the container,
The fill is set so that the components fill the full height and width of the cell.
This tutorial begins with coverage of some of the basics of Python programming. Using
Components plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
Now that we've set the dimensions of the cells, let's create some components and add them to the containers.
capabilities and shows the ways that Python interfaces with Java APIs for professional
development.
Define some sampleapplication
componentsbuttons
whose labels correspond to where they'll be added in the grid layout.

>>>
>>>
>>>
>>>

tl
tr
bl
br

=
=
=
=

Python Programming
with the Java(TM) Class Libraries: A Tutorial for Building Web
JButton("Top
Left")
and
Enterprise
Applications
JButton("Top Right") with Jython covers important topics such as:
JButton("Bottom Left")
JButton("Bottom
Right")
Fundamental programming concepts, including statements, expressions,

and compilers
Add the components to theinterpreters,
contentPane
using their corresponding GridBagConstraints.

>>>
>>>
>>>
>>>

Python basics,
including operators, string formatting, namespaces, classes, errors,
contentPane.add(tl,
top_left)
and
exceptions
contentPane.add(tr, top_right)
contentPane.add(bl,
bottom_left)
Object-oriented programming concepts
contentPane.add(br, bottom_right)

File input/output
Size the frame and show it.
Python's intrinsic functions

>>> frame.size=(400,200)
>>> frame.validate()
Formatting, parsing, and manipulating strings
>>> frame.visible=1
Interfacing with the Java APIs and working with Java Streams
If you've been following along, your frame should look like the one in Figure 14-30. Now change the size of the
container to 600,100.
Using Python and Java Swing to create GUIs
Working Figure
with SQL
and JDBC(TM)
14-30.
GridBag.py Example
Python and Java applets
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

>>> frame.size=(600,100)
Python Programming with the Java Class Libraries: A Tutorial for Building
>>> frame.validate()
Web and Enterprise Applications with Jython
By Richard Hightower

Notice that the 80:20 ratio between the top left and top right widths remains consistent. So does the 50:50 ratio
between the top left andPublisher:
bottom left
heights.
Your frame should look like the one in Figure 14-31.
Addison
Wesley
Pub Date: June 28, 2002

Table of
Contents

Figure 14-31.
GridBag.py Example with a Container Size of 600,100
ISBN: 0-201-61616-5
Pages: 640

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
Let's change the size to 500,500 so you can get the true feel of things.
This tutorial begins with coverage of some of the basics of Python programming. Using
>>> frame.size=(500,500)
plenty of skill-building exercises and interactive programming sessions, this book will
>>> frame.invalidate()
help those new to programming develop an understanding of concepts and practical
>>> frame.validate()
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities
the ways
that Python interfaces with Java APIs for professional
Try packing the frame.
What do and
you shows
think will
happen?
application development.

>>> frame.pack()
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

Adding and Removing Components

Fundamental
concepts,
includingafter
statements,
expressions,
For this next set of exercises,
we're goingprogramming
to remove and
add components
each step.
We'll define a set of
and
compilers
helper functions to do this.interpreters,
(Import them
from
GridBag.py.)

def addComponents(contentPane,
Python basics, includingcomps):
operators, string formatting, namespaces, classes, errors,
for (component,
constraint) in comps:
and exceptions
contentPane.add(component, constraint)
Object-oriented programming concepts

def removeComponents(contentPane):
input/output
#RemoveFilethe
components
for x in range (0,contentPane.componentCount):
Python's intrinsic functions
contentPane.remove(0)
Formatting, parsing, and manipulating strings
Import the addComponents() and removeComponents() functions.
Interfacing with the Java APIs and working with Java Streams

>>> from GridBag import addComponents, removeComponents


Using Python and Java Swing to create GUIs
Group component/constraint pairs into a list.
Working with SQL and JDBC(TM)

>>> comps = [(tl, top_left),(tr, top_right),(bl, bottom_left),(br,


bottom_right)]
Python and Java applets
We've essentially defined
a list ofthe
tuples,
of which
contains
WePython
can use them
In addition,
bookeach
contains
instructions
fora component
downloadingand
anda constraint.
installing the
to iterate through thelanguage
component/constraint
pairs
and
add
them
to
the
panel.
and the Java Development Kit (JDK). Terminology, definitions, explanations,

and numerous code samples make this book a useful learning experience.

for (component, constraint) in comps:


contentPane.add(component,
Whether you are a sophisticated constraint)
computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
Set the ipadx and ipady properties for the top left and top right cells, and set the fill to NONE for both. Then
give you insight into the power of Python and the know-how to put it to work.
resize the frame to 600,100, and add and remove the components from the container. (See Figure 14-32.)

777

Figure 14-32. Modified GridBag.py Example

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower
Publisher: Addison Wesley
Pub Date: June 28, 2002

>>> top_left.ipadx, top_left.ipady, top_left.fill = 10, 10,


ISBN: 0-201-61616-5
GridBagConstraints.NONE
Table of

Pages: 640
>>> Contents
top_right.ipadx, top_right.ipady, top_right.fill = 10, 10,
GridBagConstraints.NONE
Characterized by ease of use, richness of expression, and concise syntax, Python has
>>> removeComponents(contentPane)
remained a premier programming
language for more than a decade, and is used by
>>> addComponents(contentPane,
comps)
novices
and
professionals
alike.
In
particular, its close relationship to Java(TM) makes
>>> frame.size=(600,100); frame.validate()

the two languages, when used in combination, ideal for Web and distributed enterprise
application
development.
Notice that the top left
and top right
components are centered in their cells. That's because the default anchor is
CENTER. Remember that the anchor property moves the component to a particular anchor or justification
This tutorial begins with coverage of some of the basics of Python programming. Using
within a cell.
plenty of skill-building exercises and interactive programming sessions, this book will
helpfor
those
to programming
an understanding of concepts and practical
Set the anchor to EAST
thenew
top left
and top right develop
constraints.
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and
shows the ways that Python interfaces with Java APIs for professional
>>> top_left.anchor
= GridBagConstraints.EAST
application development.
>>> top_right.anchor
= GridBagConstraints.EAST

>>> removeComponents();addComponents()
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
>>> frame.invalidate()
and Enterprise Applications with Jython covers important topics such as:
>>> frame.validate()
Notice that the top left and top right components are lined up along the east borders of their cells (Figure 14-33).
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
Figure 14-33. Modified GridBag.py Example with anchor Set to EAST

Python basics, including operators, string formatting, namespaces, classes, errors,


and exceptions
Object-oriented programming concepts
File input/output

The Prototype

Python's intrinsic functions

Formatting, parsing, and manipulating strings


Now let's prototype a real application that subsets to the components the address form needs. First, though, we
Interfacing with the Java APIs and working with Java Streams
need to clean house.

>>>
>>>
>>>
>>>

frame.visible=0
Using Python and Java Swing to create GUIs
frame.dispose()
frame = NONE Working with SQL and JDBC(TM)
contentPane = NONE

Python and Java applets


Define some convenience variables for CENTER,WEST, and EAST.
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
>>> CENTER=GridBagConstraints.CENTER
and numerous code samples make this book a useful learning experience.
>>> WEST=GridBagConstraints.WEST

>>> EAST=GridBagConstraints.EAST

Whether you are a sophisticated computer user new to programming or a serious


application
developer,
Python
Programming
the Java(TM)
Classfor
Libraries
will of an
Create a 2-columnby3-row
grid
that's almost
identical
to the onewith
created
before except
the addition
givecalled
you insight
the power
of Python and
the know-how
to put it to work.
extra row at the bottom
lastinto
( last
goes underneath
bottom
).

>>>
>>> top_left
>>> top_right

# x,y,w,h
= makeConstraint(0,0,1,1, weightx=20,weighty=33, anchor=EAST
= makeConstraint(1,0,1,1, weightx=80,
anchor=WEST

777

>>> bottom_left
makeConstraint(0,1,1,1,
weighty=33,
anchor=EAST
Python=Programming
with the Java Class Libraries: A Tutorial
for Building
>>> bottom_right
= Enterprise
makeConstraint(1,1,1,1,
anchor=WEST)
Web and
Applications with Jython
>>> last
= Hightower
makeConstraint(1,2,1,1,
weighty=33)
By Richard
Define some sample components:
labels, text
fields, and a button.
Publisher: Addison
Wesley

>>>
>>>
>>>
>>>
>>>

Pub Date: June 28, 2002


tl = JLabel("Name",
JLabel.RIGHT) #Top Left component
ISBN: 0-201-61616-5
tr
=
JTextField(20)
#Top Right component
Table of
Pages: 640
bl = JLabel("eMail",
JLabel.RIGHT) #Bottom Left component
Contents
br = JTextField(30)
#Bottom Right component
Characterized by ease of use, richness of expression, and concise syntax, Python has
okay = JButton("Okay")

remained a premier programming language for more than a decade, and is used by
novices
and professionals
its close
to Java(TM)
makes
Notice that we're using
the same
nomenclaturealike.
as in In
theparticular,
last example.
Onlyrelationship
the components
are different.
the two languages, when used in combination, ideal for Web and distributed enterprise
Set up the frame withapplication
a panel that
uses GridBagLayout.
development.

>>> gbag = GridBagLayout()


This tutorial begins with coverage of some of the basics of Python programming. Using
>>> contentPane
plenty=of JPanel(layout=gbag)
skill-building exercises and interactive programming sessions, this book will
>>> frame = JFrame(contentPane=contentPane)
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
Add the sample components
to contentPane
. They
theinterfaces
same name
so we
usefor
theprofessional
capabilities
and shows the ways
thathave
Python
with
Javacan
APIs
addComponents()
method.
Group
the
components
with
the
constraints
(the
OK
button
and the last
application development.
constraint are now on the end).
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
>>> comps = [(tl,
top_left),(tr,
top_right),(bl,
bottom_left),(br,
and Enterprise
Applications with Jython
covers important topics
such as:

bottom_right),(okay,last)]
>>> addComponents(contentPane, comps)
Fundamental programming concepts, including statements, expressions,
andframe
compilers
Size the frame, and make itinterpreters,
visible. Your
should look like the one in Figure 14-34.
Python Prototype
basics, including
operators, string
formatting,
classes, errors,
Figure 14-34.
of Name/Email
Address
Booknamespaces,
Entry Form
and exceptions
Object-oriented programming concepts
File input/output
Python's intrinsic functions
Formatting, parsing, and manipulating strings
Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs
Working with SQL and JDBC(TM)

>>> frame.size=(400,200)
Python and Java applets
>>> frame.visible=1
addition,
book
contains
for downloading
installing
Python
Now let's try resizingInthe
frame tothesee
what
happensinstructions
to the components.
Change and
the frame
sizethe
to 500,500.
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
>>> frame.size=(500,500)

>>> frame.invalidate()
Whether you are a sophisticated computer user new to programming or a serious
>>> frame.validate()

application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.
Change the size to 600,100.

>>> frame.size=(600,100)
>>> frame.invalidate()
>>> frame.validate()

777

with(It
the
Java
Class
A Tutorial for Building
Now pack the frame,Python
and seeProgramming
how good it looks.
should
look
like Libraries:
Figure 14-35.)
Web and Enterprise Applications with Jython
By Richard Hightower

Figure 14-35. A Better-Looking Version of the Name/Email Address Book Entry Form
Publisher: Addison Wesley
Pub Date: June 28, 2002

Table of
Contents

ISBN: 0-201-61616-5
Pages: 640

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
>>> frame.pack()
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
Changeipadx and ipady for top_left . Space is added only to the first column, and there's more space
application development.
between the components.

>>>
>>>
>>>
>>>
>>>

This tutorial begins with coverage of some of the basics of Python programming. Using

top_left.ipadx, top_left.ipady = 20,20


plenty of skill-building exercises and interactive programming sessions, this book will
removeComponents()
help those new to programming develop an understanding of concepts and practical
addComponents()
techniques. For experienced programmers, the book demonstrates Python's breadth of
contentPane.add(okay, last)
capabilities and shows the ways that Python interfaces with Java APIs for professional
frame.pack()
application development.

ExperimentingPython Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
GridBagLayout takes some up-front planning and a lot of messing around with constraints to get what you
want, but the reward is a good-looking GUI that can be resized and still display a reasonable layout.
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
InLayout4.py, try this exercise:
Python
basics, including .operators,
string
formatting,
errors,
1. Fromlayouts select
GridBagLayout
Notice that
a 3-by-3
grid is namespaces,
defined. Youclasses,
should get
two
and
exceptions
frames that look like Figure 14-36.
Object-oriented programming concepts
Figure 14-36. Layout4.py after the Exercise
File input/output
Python's intrinsic functions
Formatting, parsing, and manipulating strings
Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs
Working with SQL and JDBC(TM)
Python and Java applets
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777
2.
3.
4.

2. Select the top Python


right component
in the components
list. Class Libraries: A Tutorial for Building
Programming
with the Java
3. Change the anchor
WEST
from theApplications
anchor list. Then
the Apply button. What happens?
Web to
and
Enterprise
withhit
Jython
4. Select the center
right component
By Richard
Hightowerfrom the components list. Then change the anchor to EAST, and hit the
Apply button. What happens?
5. Try all possible combinations
with anchor
Publisher: Addison
Wesley on several components. Then exit, and restart Layout4.py.
6. Hit the Pack button.
Select
All
from
components list. Change the fill from NONE to BOTH, and hit the
Pub Date: June 28, the
2002
Apply button. Notice ISBN:
that the0-201-61616-5
anchors for center right and top right no longer have any effect. What
Table of
happens?
Pages: 640
7. Contents
Hit Pack, and resize a few times.
8. Change the fillCharacterized
type to HORIZONTAL
; thenrichness
hit the of
Apply
button. What
happens?
by ease of use,
expression,
and concise
syntax, Python has
9. Change the anchor
to
SOUTH
;
then
hit
the
Apply
button.
What
happens?
remained a premier programming language for more than a decade, and is used by
10. Select the top novices
left component,
and set itsalike.
gridx
to 3. Whatitshappens?
Hit the Apply
button. What
and professionals
In particular,
close relationship
to Java(TM)
makes
happens? Why?
the two languages, when used in combination, ideal for Web and distributed enterprise
11. Select the top application
right component,
and set its gridx to 4. What happens? Hit the Apply button. What
development.
happens? Why?
12. Select the top This
middle
component,
and set
its gridx
to 5.ofWhat
happens?
Hit theprogramming.
Apply button.Using
What
tutorial
begins with
coverage
of some
the basics
of Python
happens? Why?
plenty of skill-building exercises and interactive programming sessions, this book will
13. Set the fill to BOTH
, andnew
thentoplay
with the insets
of allanofunderstanding
the components.
help those
programming
develop
of concepts and practical
14. Create a constraint
that spans
than one
cell.
techniques.
For more
experienced
programmers,
the book demonstrates Python's breadth of
15. Try several combinations
you getthe
theways
hangthat
of things.
be afraid
experiment.
capabilities until
and shows
Python Don't
interfaces
with to
Java
APIs for professional
application development.

Putting Things
Together: Adding GridBagLayout to the Address
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
Application and Enterprise Applications with Jython covers important topics such as:
In our last iteration of the address book application we used GridLayout for the address form pane so that
Fundamental programming concepts, including statements, expressions,
all of the text fields were the
same size.and
That's
okay for the name field, which should be about 20 characters, but
interpreters,
compilers
what about the phone number field, which should be only 13 characters? Left alone, it's about seven characters
wider than it needs to be, which
sloppy,including
not to mention
ugly.string formatting, namespaces, classes, errors,
Pythonis basics,
operators,
and exceptions
To fix the address form pane so that the text fields vary in length but are still flexible across displays, we'll use
GridBagLayout to create
a 3-by-3 grid.
The code toconcepts
do this is nearly identical to the interactive session
Object-oriented
programming
explainingGridBagLayout, so you should be able to follow along without much trouble. In case of
confusion, I've added numerous
comments.
File input/output
Review the code (from three\AddressFormPane.py),
Python's intrinsic functionsand then look at the new address book application in Figure
14-37. Also run this version of the application, and try resizing the frame to see what happens to the components.
Formatting, parsing, and manipulating strings
Figure 14-37. Address Book Entry Form with Varying-length Fields
Interfacing with the Java APIs and working with Java Streams

Using Python and Java Swing to create GUIs


Working with SQL and JDBC(TM)
Python and Java applets
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
def __init__CreateTextFieldPanel(self):
give you insight into the power of Python and the know-how to put it to work.

""" Set up the email, phoneNumber and name text fields """
# Create the panel and set the grid layout.
# The grid has a layout of a 3 rows by 2 columns.

777

editPane
= JPanel()
Python Programming
with the Java Class Libraries: A Tutorial for Building
self.cadd(editPane,
BorderLayout.CENTER)
Web and Enterprise Applications
with Jython
editPane.setLayout(GridBagLayout())
By Richard Hightower

Table of
Contents

# Set
up Wesley
some constants for the anchor.
Publisher:
Addison
CENTER=GridBagConstraints.CENTER
Pub Date: June 28, 2002
WEST=GridBagConstraints.WEST
ISBN: 0-201-61616-5
EAST=GridBagConstraints.EAST
Pages: 640
# Now let's create a 2 column by 3 row grid.
# This
will
berichness
almost
identical
to the
wehascreated
Characterized
by ease
of use,
of expression,
and concise
syntax,one
Python
#
before.
remained a premier programming language for more than a decade, and is used by
novices and professionals alike.#Inx,y,w,h
particular, its close relationship to Java(TM) makes
top_left=makeConstraint(0,0,1,1,weightx=20,weighty=33,anchor=EAST)
the two languages, when used in combination, ideal for Web and distributed enterprise
top_right
= makeConstraint(1,0,1,1,weightx=80,anchor=WEST)
application development.
CENTER_left = makeConstraint(0,1,1,1,weighty=33,anchor=EAST)
CENTER_right
makeConstraint(1,1,1,1,anchor=WEST)
This tutorial begins=with
coverage of some of the basics of Python programming. Using
bottom_left
= makeConstraint(0,2,1,1,weighty=33,
anchor=EAST)
plenty of skill-building
exercises and interactive programming sessions, this book
will
bottom_right
= makeConstraint(1,2,1,1,anchor=WEST)
help those new to programming
develop an understanding of concepts and practical
# Create
the programmers,
name textfield.
Then add
it and
techniques.
For experienced
the book demonstrates
Python's
breadthits
of
# associated
label
to the
contentPane.
capabilities
and shows the ways
that Python
interfaces
with Java APIs for professional
# Add
the label to the top_left and the __name
application
development.
# textField to the top_right.
Python Programming
with the Java(TM) Class
Libraries: A Tutorial for Building Web
self.__name
= JTextField(22,
text=self.__address.name())
and Enterprise Applications with Jython ",
covers
important topics such as:
editPane.add(JLabel("Name
JLabel.RIGHT),
top_left)
editPane.add(self.__name, top_right)
# Create the phoneNumber textfield. Then add it and
Fundamental
programming concepts,
including
expressions,
# its corresponding
label
to statements,
the contentPane.
interpreters,
and compilers
# Add the
label to the CENTER_left. Add the
#
__phoneNumber
textfield to the CENTER_right.
Python basics, including operators, string formatting, namespaces, classes, errors,
self.__phoneNumber=
and exceptions
JTextField(13,text=self.__address.phoneNumber())
editPane.add(JLabel("Phone
Number ", JLabel.RIGHT), CENTER_left)
Object-oriented programming concepts
editPane.add(self.__phoneNumber, CENTER_right)
# input/output
Create the email textfield. Then add it and its
File
# associated label to the contentPane.
Python's
# Addintrinsic
the functions
label to the bottom_left. Add the __email
# textfield to the bottom_right.
Formatting, parsing,
and manipulating strings
self.__email
= JTextField(30,
text=self.__address.email())
editPane.add(JLabel("eMail ", JLabel.RIGHT), bottom_left)
Interfacing with the Java APIs and working with Java Streams
editPane.add(self.__email, bottom_right)

Using Python and Java Swing to create GUIs


CompareFigure 14-37 to Figure 14-17, which uses GridLayout for the address form instead of
GridBagLayout. Which
do youwith
thinkSQL
looks
Working
andbetter?
JDBC(TM)

Summary

Python and Java applets

In addition, the book contains instructions for downloading and installing the Python
In this chapter, we used
the things
we've
learned
about Java
to Terminology,
add a GUI to our
address explanations,
book application.
language
and the
Java
Development
KitGUIs
(JDK).
definitions,
Along the way, we added
other
things:
a
list
to
select
address
entries
based
on
a
person's
name,
and numerous code samples make this book a useful learning experience. a toolbar,
menubar, and popup menus.
Whether you are a sophisticated computer user new to programming or a serious
With the address book
application,
we worked
withProgramming
GridLayout
,GridBagLayout
application
developer,
Python
with,FlowLayout
the Java(TM) Class
Libraries will ,
andBorderLayout
.
We
also
covered
the
ins
and
outs
of
Java
menuing
systems
and
layout
managers.
give you insight into the power of Python and the know-how to put it to work.

777

CONTENTS

Python Programming with the Java Class Libraries: A Tutorial for Building
CONTENTS
Web and Enterprise Applications with Jython
By Richard Hightower

Chapter 15. Graphics


and Events
Publisher: Addison Wesley
Pub Date: June 28, 2002

A Quick GraphicsISBN:
Tour0-201-61616-5
Table of
A Quick Tour of Pages:
Common
640 Events
Contents
Putting Things Together: A Drawing Program
Characterized
by ease
of use, richness
of expression, and concise syntax, Python has
The Complete
Shapes and
DrawShapes
Modules
remained a premier programming language for more than a decade, and is used by
Summary

novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
Terms in This Chapter
application development.
This
tutorial begins with coverage of someInput
of thefocus
basics of Python programming. Using
Coupling
plenty of skill-building exercises and interactive programming sessions, this book will
Encapsulation
help
those new to programming develop anModularity
understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
Event-drivenand
programming
capabilities
shows the ways that PythonPolyline
interfaces with Java APIs for professional
application development.
Event model
Scaffolding code
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
Graphics
objectApplications with Jython covers
Staticimportant
versus interactive
m ode
and
Enterprise
topics such
as:
Hit testing
Unit level test
Fundamental programming concepts, including statements, expressions,
In this chapter, we'll learn the
basics of and
events
and graphics. These are the things you'll need to know when you
interpreters,
compilers
write your own graphical components. In particular, you'll need to understand the event model and some
rudimentary graphics programming.
In a later
chapter,
we'll seestring
how formatting,
to package namespaces,
your component
in a Java
bean
Python basics,
including
operators,
classes,
errors,
so you can distribute it to the
andunsuspecting
exceptions world. We're just scratching the surface of graphics in this book.

Object-oriented programming concepts


A Quick Graphics
Tour
File input/output
Every AWT component has a method called getGraphics(), which returns the instance of the graphics
Python's
intrinsic
object associated with it. The
graphics
objectfunctions
allows you to draw on the component. With the
java.awt.Graphics object you can draw arcs, images, lines, ovals, polylines, and such. We can't cover
parsing,
manipulating
strings
all of the possibilities, onlyFormatting,
enough to whet
yourand
appetite.
Later we'll
build a drawing package that works with
text, rectangles, circles, and ovals. For now, let's do an interactive session that introduces drawing on a
Interfacing with the Java APIs and working with Java Streams
component.
Python
Java use
Swing
GUIs
Import a frame, and create Using
an instance
ofand
it. We'll
it totodocreate
our drawing.
Workingimport
with SQLJFrame,
and JDBC(TM)
>>> from javax.swing
JPanel
>>> frame = JFrame("Drawing", size=(400,400), visible=1)
Python and Java applets

>>> graphics In=addition,


frame.contentPane.graphics
the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
Get the graphics instance from the frame, and draw a line, but first make sure that no other window is
and numerous code samples make this book a useful learning experience.
obscuring the frame. You may have to reduce the size of the window that contains the Jython prompt for this.
Whether you are a sophisticated computer user new to programming or a serious
Draw a line with starting coordinates of 50,50 and ending coordinates of 200,200 (in pixels).
application developer, Python Programming with the Java(TM) Class Libraries will
you insight into the power of Python and the know-how to put it to work.
>>> graphics give
= frame.getGraphics()()

>>> graphics.drawLine(50, 50, 200,200)

777

Draw a circle (actually an oval with equal width and height).

>>> graphics.drawOval(50,50,300,300)
Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython

To put text on the frame,


pass the
starting coordinates and the string you want to draw to the graphic's
By Richard
Hightower
drawString() method. The string will be in the component's current font. Draw a string with starting
coordinates of 50,50. Publisher: Addison Wesley
Pub Date: June 28, 2002
>>> graphics.drawString("Hello
World", 50,50)
Table of
a string with
Draw
Contents

ISBN: 0-201-61616-5
640
startingPages:
coordinates

of 75,75.

>>> graphics.drawString("I
75,75)
Characterized by ease ofam
use,late
richnessagain",
of expression,
and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
Draw a string with starting
of 200,200.
novicescoordinates
and professionals
alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
>>> graphics.drawString("Hello
Cruel World", 200, 200)
application development.
We can draw filled shapes
as wellbegins
as outlines.
We can also
change
color
by setting
the graphics
color property.
This tutorial
with coverage
of some
of the
basics
of Python
programming.
Using
Draw an oval.
plenty of skill-building exercises and interactive programming sessions, this book will

help those new to programming develop an understanding of concepts and practical


techniques. For experienced programmers, the book demonstrates Python's breadth of
Draw a blue oval. capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.

>>> graphics.fillOval(150,150, 50, 100)

>>> from java.awt import Color


Python Programming
with the Java(TM) Class Libraries: A Tutorial for Building Web
>>> graphics.color
= Color.blue
and
Enterprise
Applications
Jython50)
covers important topics such as:
>>> graphics.fillOval(150,150,with
100,
Dispose of the graphics resource. You must always do this when you're done with your drawing.
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
>>> graphics.dispose()

Python
basics,
operators,
stringorformatting,
Your frame should look like
Figure
15-1. including
Notice that,
if you resize
obscure thenamespaces,
frame with classes,
another errors,
window,
and
exceptions
the image is erased. This simply won't do. We need something a little less transitive, which gets us back to eventdriven programming. Enter the paint() method, which will tell us when the window needs to be redrawn so
Object-oriented programming concepts
that we can take the necessary action.
File input/output
Figure 15-1. Outlined and Filled Shapes
Python's intrinsic functions
Formatting, parsing, and manipulating strings
Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs
Working with SQL and JDBC(TM)
Python and Java applets
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower
Publisher: Addison Wesley
Pub Date: June 28, 2002

Table of
Contents

ISBN: 0-201-61616-5
Pages: 640

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
A component (window, frame, panel, etc.) is notified that its window needs to be redrawn via the paint()
method. paint() is passed
a Graphics
class instance
that refers
to the
current component.
With
Fundamental
programming
concepts,
including
statements,
expressions,
paint(), you don't dispose
of
this
instance
when
you're
done.
interpreters, and compilers
Here's an example of the paint()
method
(class operators,
DrawPicture
from draw2.py)
showing
how iterrors,
redraws
Python basics,
including
string formatting,
namespaces,
classes,
the image we created in ourand
first
session. This time we'll be able to resize and obscure the window, and it will
exceptions
always redraw the picture properly.
Object-oriented programming concepts

from javax.swing import JFrame


from java.awt import
Color
File input/output
Python's intrinsic functions
class DrawPicture(JFrame):
def __init__(self):
Formatting, parsing, and manipulating strings size=(400,400), visible=1)
JFrame.__init__(self,"Drawing",
def closing(event):
Interfacing with the Java APIs and working with Java Streams
from java.lang import System
Using System.exit(0)
Python and Java Swing to create GUIs
self.windowClosing = closing
Working with SQL and JDBC(TM)

def paint(self,graphics):
line and a circle.
Python#Draw
and Javaaapplets
graphics.drawLine(50, 50, 200,200)
Ingraphics.drawOval(50,50,300,300)
addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous
code samples
this book a useful learning experience.
#Draw
somemake
strings

graphics.drawString("Hello World", 50,50)

Whether
you are a sophisticated computer
new again",
to programming
or a serious
graphics.drawString("I
am user
late
75,75)
application
developer,
Python
Programming
with
the
Java(TM)
Class
Libraries
will
graphics.drawString("Hello Cruel World", 200,
200)
give you insight into the power of Python and the know-how to put it to work.

#Draw an Oval
graphics.fillOval(150,150, 50, 100)

777

#Draw a Blue Oval

graphics.color
Color.blue
Python Programming =
with
the Java Class Libraries: A Tutorial for Building
graphics.fillOval(150,
150,
100, 50)
Web and Enterprise Applications with
Jython
if __name__ ==
'__main__':
By Richard
Hightower
d = DrawPicture()
Publisher: Addison Wesley

The frame should now look


like Figure 15-2. Notice that you can resize it and obscure it with other windows.
Pub Date: June 28, 2002
Every time you return to the picture, it will be just like it was when you left it.

Table of
Contents

ISBN: 0-201-61616-5

Pages: 640

Figure 15-2. Figure 15-1 Redrawn with the paint() Method

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
Object-oriented programming concepts
File input/output
That was a painless introduction to graphics programming. Look up java.awt.Graphics in the Java API
Python's intrinsic functions
documentation; you'll see that we've covered only a fraction of what you can do with it. You may also want to
learn about the 2D and 3D Formatting,
APIs.
parsing, and manipulating strings

with the
Java APIs and working with Java Streams
A Quick Tour ofInterfacing
Common
Events
Using Python and Java Swing to create GUIs
Table 15-1 lists common events and their corresponding event properties. Table 15-2 lists common events and
the first component in the class
hierarchy
to which
each event maps. The first thing you may notice in Table 15-2
Working
with SQL
and JDBC(TM)
is that some components are missing, such as JFrame and, for that matter, Frame. Remember, though, that
Python ,and
JFrame is a subclass of Frame
andJava
thatapplets
Frame is a subclass of Window. Thus, JFrame publishes
window events through the Window's interface, WindowListener.
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous
code samples
makeEvents
this bookand
a useful
Table
15-1. Common
Graphics
Theirlearning
Eventexperience.
Properties
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Event

Listener Interface
PropertyA Tutorial for Building
Python Programming
with the Java Class Libraries:
Web and Enterprise
Applications
with
Jython
ActionListener
actionPerformed
By Richard Hightower

ActionEvent
AdjustmentEvent
AdjustmentListener
ComponentEventPublisher:
ComponentListener
Addison Wesley
Pub Date: June 28, 2002

Table of
Contents

adjustmentValueChanged
componentHidden
componentMoved

ISBN: 0-201-61616-5
Pages: 640

componentResized

componentShown
Characterized by ease of use, richness of expression,
and concise syntax, Python has
remained
a
premier
programming
language
for
more
than
a decade, and is used by
ContainerEvent
ContainerListener
componentAdded
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal
for Web and distributed enterprise
componentRemoved
application
development.
FocusEvent
FocusListener
focusGained

ItemEvent
KeyEvent

This tutorial begins with coverage of some of the basics


of Python programming. Using
focusLost
plenty of skill-building exercises and interactive programming sessions, this book will
ItemListener
itemStateChanged
help those new to programming develop an understanding of concepts and practical
keyPressed
techniques. KeyListener
For experienced programmers, the book
demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
keyReleased
application development.

MouseEvent

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
MouseListener
mouseClicked
and Enterprise
Applications with Jython covers important
topics such as:

keyTyped

mouseEntered
Fundamental programming concepts, including statements, expressions,
mouseExited
interpreters, and compilers

mousePressed
Python basics, including operators, string formatting,
namespaces, classes, errors,
and exceptions
MouseEvent

Object-oriented
programming concepts
MouseMotionListener
File input/output

TextEvent
WindowEvent

TextListener
Python's intrinsic functions
WindowListener

mouseReleased
mouseDragged

mouseMoved
textValueChanged
windowActivated

Formatting, parsing, and manipulating strings

windowClosed

Interfacing with the Java APIs and working with Java Streams

windowClosing

Using Python and Java Swing to create GUIs

windowDeactivated

Working with SQL and JDBC(TM)


Python and Java applets

windowDeiconified
windowIconified

In addition, the book contains instructions for downloading and installing the Python
windowOpened
language and the Java Development Kit (JDK). Terminology,
definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
Table 15-2.
Common
Graphic
Events
and Their
Hierarchy
give you
insight into
the power
of Python
and theClass
know-how
to put itMappings
to work.

777

Component

Event Published
Listener
MeaningA Tutorial for Building
Python Programming
withthrough
the Java
Class Libraries:
Web
and
Enterprise
Applications
with
Jython
AbstractButton
ActionEvent,
User clicked button
By Richard
Hightower
ActionListener

JButton

ActionEvent,
ActionListener
Pub Date: June 28, 2002
JCheckBox
ItemEvent, ItemListener
ISBN: 0-201-61616-5
Table of
JCheckBoxMenuItem
ItemEvent,
ItemListener

Pages:
640
Publisher: Addison Wesley

Contents

Component

Container

User clicked button


User selected or unselected checkbox
User selected or unselected

CheckboxMenuItem

ComponentEvent,
Component
moved,
shown, or
Characterized
by ease of use, richness of expression,
and concise
syntax,resized
Python has
hidden
remainedComponentListener
a premier programming language for more
than a decade, and is used by
novices and
professionals alike. In particular, its close
relationship
FocusEvent,
Component
losttoorJava(TM)
got focusmakes
the two languages,
when
used
in
combination,
ideal
for
Web
and
distributed
enterprise
FocusListener
application
development.
MouseEvent,
User clicked, pressed, and released
mouse, and mouse cursor entered or
MouseListener
This tutorial begins with coverage of some of the basics of Python programming. Using
exited component
plenty of skill-building exercises and interactive programming sessions, this book will
MouseEvent,
User moved
mouseand
in component,
help those new to programming develop an understanding
of concepts
practical
and dragged mouse, i.e., pressed
MouseMotionListener
techniques. For experienced programmers, the book demonstrates Python's breadth of
button while moving mouse cursor
capabilities and shows the ways that Python interfaces with Java APIs for professional
ContainerEvent,
Component added or removed
application
development.

ContainerListener

JComboBox

JList

JMenuItem
JScrollBar
JTextField
Window

Python Programming
with the Java(TM) Class Libraries:
A Tutorial for Building Web
ActionEvent,
Item double-clicked
and Enterprise
Applications
with
Jython
covers
important
topics
such as:
ActionListener

ItemEvent, ItemListener Item selected or unselected


ListSelectionEvent,
Itemstatements,
double-clicked
Fundamental
programming concepts, including
expressions,
ListSelectionListener
interpreters, and compilers
ItemEvent, ItemListener Item selected or unselected
Python basics, including operators, string formatting, namespaces, classes, errors,
ActionEvent,
Menu item selected
and exceptions
ActionListener
AdjustmentEvent,
User moved scrollbar
Object-oriented
programming concepts
AdjustmentListener
File
input/output
ActionEvent,
User pressed Enter in text box
ActionListener
Python's intrinsic functions
WindowEvent,
Window was opened, closed,
iconified, restored, or a close was
WindowListener
Formatting,
parsing, and manipulating strings

requested
Interfacing with the Java APIs and working with Java Streams
It doesn't stop there. Window is a subclass of Container, so JFrame publishes container events through
Usinginterface
Python and
JavaAnd,
Swing
toother
createcomponents,
GUIs
theContainerListener
as well.
like
JFrame is a subclass of
Component, so it publishes component events through the ComponentListener interface, focus events
Working
with SQL
JDBC(TM)
through the FocusListener
interface,
andand
mouse
events through the MouseListener and
MouseMotionListener interfaces (Container is a direct subclass of Component). The point is
Python and Java applets
that a component doesn't just publish the events it defines; it publishes all events from its hierarchy of
superclasses.
In addition, the book contains instructions for downloading and installing the Python

language and the Java Development Kit (JDK). Terminology, definitions, explanations,
Another example of this is JButton, which is a subclass of AbstractButton, which is a subclass of
and numerous code samples make this book a useful learning experience.
JComponent, which is a subclass of Container, which is a subclass of Component. As such, it
publishes all of the events
thatyou
its superclasses
define.computer user new to programming or a serious
Whether
are a sophisticated
application developer, Python Programming with the Java(TM) Class Libraries will

An Event Frame
give you insight into the power of Python and the know-how to put it to work.
Let's create a frame that handles every possible eventthat is, essentially, one frame that handles every event
mentioned in the last section that Frame supports. We'll use the Frame class in java.awt (from which Swing
gets much of its behavior and design). Examine the source code closely (it's from FrameEvents.py). Later we'll

777

break it down.

from

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
java.awtByRichard
import
Frame, List, Panel, Button, FlowLayout, BorderLayout
Hightower

class EventFrame(Frame):
Publisher: Addison Wesley
def __init__(self,
event_viewer):
Pub Date: June 28, 2002
Frame.__init__(self, "Event Frame")

Table of
Contents

ISBN: 0-201-61616-5

Pages: 640

self.event_viewer = event_viewer
self.layout = FlowLayout()

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
#ComponentEvent publishes to ComponentListener
novices and professionals alike. In particular, its close relationship to Java(TM) makes
self.componentHidden = self.__handle_event
the two languages, when used in combination, ideal for Web and distributed enterprise
self.componentMoved = self.__handle_event
application development.

self.componentResized = self.__handle_event
self.componentShown
= ofself.__handle_event
This tutorial begins with coverage
some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
publishes
to ContainerListener
help those#ContainerEvent
new to programming develop
an understanding
of concepts and practical
self.componentAdded
=
self.__handle_event
techniques. For experienced programmers, the book demonstrates Python's breadth of
self.componentRemoved
self.__handle_event
capabilities and shows the ways that=Python
interfaces with Java APIs for professional
application development.

#FocusEvent publishes to FocusListener


self.focusGained
= self.__handle_event
Python Programming with the
Java(TM) Class Libraries: A Tutorial for Building Web
self.focusLost
= self.__handle_event
and Enterprise Applications
with Jython covers important topics such as:
#KeyEvent publishes to KeyListener
Fundamental programming
concepts, including statements, expressions,
self.keyPressed
= self.__handle_event
interpreters, and compilers
self.keyReleased
= self.__handle_event
self.keyTyped = self.__handle_event

Python basics, including operators, string formatting, namespaces, classes, errors,


and#MouseEvent
exceptions
publishes to MouseListener

self.mouseClicked
= self.__handle_event
Object-oriented programming concepts
self.mouseEntered = self.__handle_event
self.mouseExited
= self.__handle_event
File input/output
self.mousePressed = self.__handle_event
self.mouseReleased
= self.__handle_event
Python's intrinsic functions
Formatting,
parsing, andpublishes
manipulating strings
# MouseEvent
to MouseMotionListener
self.mouseDragged = self.__handle_event
Interfacing with the=Java
APIs and working with Java Streams
self.mouseMoved
self.__handle_event
Using Python and Java Swing to create GUIs

# WindowEvent publishes to WindowListener


self.windowActivated
= self.__handle_event
Working with SQL and JDBC(TM)
self.windowClosed = self.__handle_event
self.windowClosing
Python and Java applets = self.__handle_event
self.windowDeactivated = self.__handle_event
self.windowDeiconified
= self.__handle_event
In addition, the book contains instructions
for downloading and installing the Python
self.windowIconified
= Kit
self.__handle_event
language and the Java Development
(JDK). Terminology, definitions, explanations,
self.windowOpened
= self.__handle_event
and numerous code samples make
this book a useful learning experience.
Whether
you are a sophisticated computer user new to programming or a serious
self.size=(100,100)
application developer, Python Programming with the Java(TM) Class Libraries will
self.visible=1
give you insight into the power of Python and the know-how to put it to work.

#handles all of the events in this demo


def __handle_event(self, event):
self.event_viewer.addEvent(event)

777

. . .
. . .

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

class EventViewer(Frame):
def __init__(self,
close):
Publisher: Addison
Wesley
Frame.__init__(self,"Event
Viewer")
Pub Date: June 28, 2002

Table of
Contents

ISBN: 0-201-61616-5

# Create a list to display events


self.__list = List()
self.add(self.__list,
BorderLayout.CENTER)
Characterized by ease of use, richness
of expression, and concise syntax, Python has
Pages: 640

remained a premier programming language for more than a decade, and is used by
# professionals
Set up toolbar
to addits close
and relationship
remove to
components
from frame
novices and
alike. In particular,
Java(TM) makes
add
= languages,
Button("Add")
the two
when used in combination, ideal for Web and distributed enterprise
add.actionPerformed
= self.__handle_add
application development.

remove = Button("Remove")
remove.actionPerformed
self.__handle_remove
This tutorial begins with coverage of =
some
of the basics of Python programming. Using
tool_pane
= Panel()
plenty of skill-building
exercises and interactive programming sessions, this book will
tool_pane.add(add)
help those new to programming develop an understanding of concepts and practical
tool_pane.add(remove)
techniques. For experienced programmers, the book demonstrates Python's breadth of
self.add(tool_pane,
capabilities and shows the ways BorderLayout.NORTH)
that Python interfaces with Java APIs for professional
self.size=(500,400)
application development.
self.visible=1
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
self.location=(300,300)
Applications with Jython covers important topics such as:
.and.Enterprise
.
def addEvent(self, event):
Fundamental programming concepts, including statements, expressions,
self.__list.add(`event`,0)
interpreters, and compilers

#add Python
a component
to the frame
basics, including operators, string formatting, namespaces, classes, errors,
def __handle_add(self,
event):
and exceptions
global frame
frame.add(Button(`frame.componentCount`))
Object-oriented programming concepts
frame.invalidate();frame.validate()
File input/output

#removes a component from the frame


Python's intrinsic functionsevent):
def __handle_remove(self,
if (frame.componentCount > 0):
Formatting,
parsing, and manipulating strings
frame.remove(frame.componentCount-1)
frame.invalidate();frame.validate()

Interfacing with the Java APIs and working with Java Streams

if __name__ == '__main__':
Using Python and Java Swing to create GUIs
viewer = EventViewer(close)
frame = EventFrame(viewer)
Working with SQL and JDBC(TM)
Python
and Java applets
Window Events with
EventFrame
In addition, the book contains instructions for downloading and installing the Python
The code for our example is pretty simple. In the constructor of the EventFrame class, we register for every
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
event that Frame publishes. All of the events are registered to the same event handler method,
and numerous code samples make this book a useful learning experience.
__handle_event().
Whether you are a sophisticated computer user new to programming or a serious

#handles
all of the events in this demo
application developer, Python Programming with the Java(TM) Class Libraries will
def __handle_event(self,
event):
give you insight into the power of Python and the know-how to put it to work.
self.event_viewer.addEvent(event)

777

The event handler calls self.event_viewer.addEvent, which adds the event to a listbox so we can
view it. addEvent() forces the event to the top of the list, using back quotes to get its string representation.

def addEvent(self,
event): with the Java Class Libraries: A Tutorial for Building
Python Programming
self.__list.add(`event`,0)
Web and Enterprise Applications with Jython
By Richard Hightower

Now let's use EventFrame to examine all of the events that the frame handles:
Publisher: Addison Wesley
Pub Date: June 28, 2002
windowActivated

ISBN: 0-201-61616-5
Table of
windowClosed
Pages: 640
Contents

windowClosing
Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by

windowDeactivated
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.

windowDeiconified
windowIconified

This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
windowOpened
help those new to programming develop an understanding of concepts and practical
techniques. ,For
the book demonstrates
Python'scomes
breadthup,ofwe get
To use WindowActivated
all experienced
we need to doprogrammers,
is start EventFrames.py.
When the window
capabilities
and
shows
the
ways
that
Python
interfaces
with
Java
APIs
for
professional
the following events:
application development.

java.awt.event.WindowEvent[WINDOW_ACTIVATED]
onTutorial
frame0
Python Programming with the Java(TM) Class Libraries: A
for Building Web
and Enterprise Applications with Jython covers important topics such as:

java.awt.event.FocusEvent[FOCUS_GAINED,permanent] on frame0
java.awt.event.ComponentEvent[COMPONENT_SHOWN]
onexpressions,
frame0
Fundamental programming concepts, including statements,
interpreters, and compilers

java.awt.event.WindowEvent[WINDOW_OPENED] on frame0
Python basics, including operators, string formatting, namespaces, classes, errors,

WindowEvent, with itsand


ID set
to WINDOW_ACTIVATED, corresponds to the windowActivated
exceptions
event property of the frame. This pattern repeats itself for all event properties and event IDs. Notice that, in
addition to windowOpened
and windowActivated
,Frame publishes focusGained and
Object-oriented
programming concepts
componentShown.
File input/output
When the focus changes to another window, you get the following windowDeactivated events. Click on
Python's intrinsic functions
the caption of the event viewer.

Formatting, parsing, and manipulating strings

java.awt.event.WindowEvent[WINDOW_DEACTIVATED] on frame0
Interfacing with the Java APIs and working with Java Streams

java.awt.event.FocusEvent[FOCUS_LOST,temporary] on frame0
Using Python and Java Swing to create GUIs
To get a windowIconified event, we have to minimize the window by clicking the Minimize button on
Working
with
SQL
and JDBC(TM)
the right side of the window's
caption.
The
following
events result:
Python and Java applets

java.awt.event.FocusEvent[FOCUS_LOST,temporary] on frame0
In addition, the book contains instructions for downloading and installing the Python

java.awt.event.WindowEvent[WINDOW_ICONIFIED]
ondefinitions,
frame0explanations,
language and the Java Development Kit (JDK). Terminology,
and numerous code samples make this book a useful learning experience.

java.awt.event.WindowEvent[WINDOW_DEACTIVATED] on frame0
Whether you are a sophisticated computer user new to programming or a serious
Now we want to restore
the frame,
so we goPython
to the Programming
taskbar and click
icon.Class
These
are the events
application
developer,
withthe
theFrames
Java(TM)
Libraries
will we
get:
give you insight into the power of Python and the know-how to put it to work.

777

java.awt.event.WindowEvent[WINDOW_ACTIVATED] on frame0
java.awt.event.WindowEvent[WINDOW_DEICONIFIED] on frame0

Python Programming with the Java Class Libraries: A Tutorial


Building
java.awt.event.FocusEvent[FOCUS_GAINED,permanent]
onforframe0
Web and Enterprise Applications with Jython
By Richard Hightower

Then we click the window's Close button to get the windowClosing event:
Publisher: Addison Wesley

java.awt.event.WindowEvent[WINDOW_CLOSING]
on frame0
Pub Date: June 28, 2002
ISBN: 0-201-61616-5

Tableisof
Theevent
a request to close, not the actual closing. For that we have to restart the application in the interactive
Pages: 640
Contents
interpreter
and type

Characterized
>>> frame.visible
= 0 by ease of use, richness of expression, and concise syntax, Python has
remained
a premier programming language for more than aon
decade,
and is used by
java.awt.event.ComponentEvent[COMPONENT_HIDDEN]
frame0

novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
>>> frame.dispose()
application development.
java.awt.event.WindowEvent[WINDOW_CLOSED]
on frame0
This close
tutorial
with coveragefunction
of somedoes
of the
basics of Python programming. Using
Hiding the frame doesn't
it. begins
The dispose()
that.
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
Container Events
withFor
EventFrame
techniques.
experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
On the event viewerapplication
window aredevelopment.
the Add and Remove buttons, which add components to and remove them from
the frame. If you hit Add twice and Remove twice, you'll get the following events:
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

java.awt.event.ContainerEvent[COMPONENT_ADDED,child=button0] on
frame0
Fundamental programming concepts, including statements, expressions,

java.awt.event.ContainerEvent[COMPONENT_ADDED,child=button1]
on
interpreters, and compilers
frame0
Python basics, including operators, string formatting, namespaces, classes, errors,

java.awt.event.ContainerEvent[COMPONENT_REMOVED,child=button1]
and exceptions
on frame0
Object-oriented programming concepts

java.awt.event.ContainerEvent[COMPONENT_REMOVED,child=button0]
on frame0
File input/output
Python's intrinsic functions
Key Events with EventFrame
Formatting, parsing, and manipulating strings
If you make the frame the active window and press the A key, you should get the following events:
Interfacing with the Java APIs and working with Java Streams

java.awt.event.KeyEvent[KEY_PRESSED,keyCode=65,keyChar='a']
on
Using Python and Java Swing to create GUIs
frame0
Working with SQL and JDBC(TM)

java.awt.event.KeyEvent[KEY_TYPED,keyCode=0,keyChar='a'] on
frame0
Python and Java applets
java.awt.event.KeyEvent[KEY_RELEASED,keyCode=65,keyChar='a']
In addition, the book contains instructions for downloading and installing the Python on
frame0
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
If you hold the key down, you'll get keyPressed and keyTyped , but you won't get keyReleased.
Whether you are a sophisticated computer user new to programming or a serious
As an exercise, lookapplication
up KeyListener
the Java
API documentation.
Note the difference
between
developer, in
Python
Programming
with the Java(TM)
Class Libraries
will
keyPressed andgive
keyTyped
.
If
you
want
to
create
a
typing
program,
which
event
do
you
handle for
you insight into the power of Python and the know-how to put it to work.
capturing alphanumeric characters? Which one for handling special keys like Enter and Backspace? You'll need
to know this later.

777

Mouse Events from FrameEvent

Python Programming with the Java Class Libraries: A Tutorial for Building

If you click in the FrameEvent frame, you'll get the mousePressed,mouseClicked, and
Web and Enterprise Applications with Jython
mouseReleasedBymouse
events. If you hold the mouse button down and drag it, you'll get the
Richard Hightower
mouseDragged event. If you move the mouse pointer anywhere in the work area of the frame (or any place
but the caption [titlebar] and system menus), you'll get the mouseMoved event. Table 15-3 lists the mouse
Publisher: Addison Wesley
events.
Pub Date: June 28, 2002

Try these
exercises:
Table
of

Contents

ISBN: 0-201-61616-5
Pages: 640

Click on the frame's


work area
therichness
right and
left buttons.
difference
in has
the output?
Characterized
by with
ease both
of use,
ofthe
expression,
and What's
concisethe
syntax,
Python
remained a premier programming language for more than a decade, and is used by
This sample application
written in AWT
arerelationship
similar to Swing
components.
novices andwas
professionals
alike.components,
In particular,which
its close
to Java(TM)
makes
Convert to JFC/Swing.
(The component
events
must be set upideal
withfor
JFrame
.)
the two languages,
when used
in combination,
Web and'scontentPane
distributed enterprise

application development.

Event

MouseEvent

Table
15-3.with
Mouse
Events
andofEvent
Properties
This tutorial
begins
coverage
of some
the basics
of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new
to programming
of concepts and practical
Listener
Interface develop an understandingProperty
techniques.MouseListener
For experienced programmers, the book demonstrates
Python's breadth of
mouseClicked
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
mouseEntered

Python Programming with the Java(TM) Class Libraries:mouseExited


A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

mousePressed

MouseEvent

Fundamental programming concepts, including statements,


expressions,
mouseReleased
interpreters,
and compilers
mouseMotionListener
mouseDragged
Python basics, including operators, string formatting,
namespaces, classes, errors,
mouseMoved
and exceptions
Object-oriented programming concepts
File input/output

AWT
or
Python's To
intrinsic
functions

Not to AWT

Formatting,
parsing,
Many of the concepts
in Swing and
AWTand
aremanipulating
very similar. strings
Most of the examples in this book are
written in Swing because that's the dominant choice for the Java Standard Edition. However, for
Interfacing with the Java APIs and working with Java Streams
the Java Micro edition (Windows CE and handheld devices) AWT is still the best. That's why I
used it for some of the
examples.
Using
Python and Java Swing to create GUIs
Working with SQL and JDBC(TM)

Putting Things Together: A Drawing Program


Python and Java applets
Although not as ubiquitous as the famous "Hello World", the sample application explained in the
addition,
the book
contains
downloading
and
installing
following sections isInquite
common.
We want
it to instructions
draw ovals, for
rectangles,
circles,
and
so forth.the
I'vePython
opted for
language
and
the
Java
Development
Kit
(JDK).
Terminology,
definitions,
explanations,
simplicity rather than perfection in my design. Later I'll point out what's wrong with it.
and numerous code samples make this book a useful learning experience.
We'll incorporate ideas from many chapters in our program, which we'll develop in two modules and three
Whether
you are
a sophisticated
computer
new to programming
a serious
phases. The first phase
is a simple
application
that draws
ovals user
and rectangles.
The secondorphase
will add circles,
application
developer,
Python
Programming
with
the
Java(TM)
Class
Libraries
will"glyph.")
squares, rounded rectangles, and text. (I know text isn't a shape, but I don't like the correct terminology,
give
you
insight
into
the
power
of
Python
and
the
know-how
to
put
it
to
work.
The third phase will correct a serious design flaw introduced in the first and second phases.
The first module, Shapes, contains all of the graphics. The second module, DrawShapes, defines the user
interface, that is, the event handling and the component container layout.

777

Phase 1: Shapes
Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard
Hightower
TheShapes module contains
four
main classes: Shape,Rectangle,Oval,

and Shapes.Shape is the


superclass of the others; it defines the interface that all shape classes use so they all can be treated
Publisher:
Addison
polymorphically (one can
be replaced
with Wesley
another). Rectangle inherits most of its functionality from
Date: June
28, 2002
Shape, as does OvalPub
.Shapes
represents
a collection of shape objects and implements the Shape
ISBN: 0-201-61616-5
interface.

Table of
Contents

Pages: 640

TheShape class defines three methods:


Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
The constructorstores shape parameters like x, y position, dimensions (width, height), and color
novices and professionals alike. In particular, its close relationship to Java(TM) makes
two languages,awhen
combination,
idealcontext
for Web and distributed enterprise
Thepaint()the
methodpaints
shapeused
usinginthe
given graphics
application development.
Thedraw_filled() methoddraws a filled shape
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building
exercises
interactive
programming sessions, this book will
Thedraw_outline()
methoddraws
theand
outline
of a shape
help those new to programming develop an understanding of concepts and practical
The constructor stores
five values:
position, width,
height, color,
and fill/nofill.
Here's
some of
its code.
techniques.
Forx,yexperienced
programmers,
the book
demonstrates
Python's
breadth
of (All
of the following examples
are from
capabilities
andOne\Shape.py.)
shows the ways that Python interfaces with Java APIs for professional
application development.

class Shape:
def __init__(self,
x, the
y, Java(TM)
width=0,
color=None,
fill=0):
Python Programming with
Class height=0,
Libraries: A Tutorial
for Building Web
self.x=x
and
Enterprise Applications with Jython covers important topics such as:
self.y=y
self.width=width
Fundamental programming concepts, including statements, expressions,
self.height=height
interpreters, and compilers
self.color=color
self.fill=fill
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
paint() paints on the given
graphics context and so takes a graphics object as an argument. It also checks to
see if a color was assigned; if so, it sets the graphics color property to the shape color property and saves the
Object-oriented programming concepts
original color to be restored later. If the fill attribute is true, paint()calls the draw_filled()
method; otherwise, it calls File
the draw_outline()
method.
input/output
paint() Code and Breakdown
Python's intrinsic functions

Formatting,
parsing, and manipulating strings
Here's the code for paint()
:
with the Java APIs and working with Java Streams
def paint (self, Interfacing
graphics):
Using Pythonis
andNone:
Java Swing to create GUIs
if not self.color
oldcolor = graphics.color
Working with SQL and JDBC(TM)
graphics.color = self.color
Python and Java applets

if self.fill:
Inself.draw_filled
addition, the book contains(graphics)
instructions for downloading and installing the Python
else: language and the Java Development Kit (JDK). Terminology, definitions, explanations,
self.draw_outline(graphics)
and
numerous code samples make this book a useful learning experience.
you are a sophisticated
if not Whether
self.color
is None: computer user new to programming or a serious
application
developer, Python
Programming with the Java(TM) Class Libraries will
graphics.color
= oldcolor
give you insight into the power of Python and the know-how to put it to work.

draw_filled() and draw_outline()draw the shape as filled or outlined, respectively. They're


abstract, meaning that they don't do anything until they're defined by subclasses of Shape. This makes sense
when you think about itfor example, only the Rectangle class knows how to draw a rectangle.

777

Here are the two drawing


methods
as definedwith
by Shape
:
Python
Programming
the Java

def

Class Libraries: A Tutorial for Building


Web and Enterprise Applications with Jython
draw_filled(self,
graphics):
By Richard Hightower

pass
Publisher: Addison Wesley

def draw_outline(self,
graphics):
Pub Date: June 28, 2002
pass
ISBN: 0-201-61616-5
Table of
Pages:
Thedraw_outline()
method640
gets the bounds
Contents

of the shape: position (x,y) and dimensions (width, height).


We'll use these to calculate the area of the window that needs to be redrawn. First, we need the getRect()
Characterized by ease of use, richness of expression, and concise syntax, Python has
function.
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
def getRect(self):
two languages,
when usedself.width,
in combination, ideal
for Web and distributed enterprise
returntheself.x,
self.y,
self.height
application development.
BothRectangle and Oval subclass Shape, and both implement the abstract methods
begins with coverage
of some ofthem,
the basics
of Python programming.
Using
draw_filled()This
andtutorial
draw_outline()
. To implement
the Rectangle
class uses the
plenty
of
skill-building
exercises
and
interactive
programming
sessions,
this
book
will uses
java.awt.Graphics methods fillRect() and drawRect(), respectively; the Oval class
help
those
new
to
programming
develop
an
understanding
of
concepts
and
practical
fillOval() and drawOval().
techniques. For experienced programmers, the book demonstrates Python's breadth of
Here are the Rectangle
and and
Oval
classes:
capabilities
shows
the ways that Python interfaces with Java APIs for professional
application development.

class Rectangle(Shape):
def __init__(self,
x, the
y, Java(TM)
width,Class
height,
fill=0):
Python Programming with
Libraries:color=None,
A Tutorial for Building
Web
x, covers
y, width,
height,
andShape.__init__(self,
Enterprise Applications with Jython
important topics
such as:color, fill)
def draw_filled(self,graphics):
Fundamental programming concepts, including
statements,
expressions,self.height)
graphics.fillRect(self.x,
self.y,
self.width,
interpreters, and compilers

def draw_outline(self,graphics):
Python basics, including operators, string formatting, namespaces, classes, errors,
graphics.drawRect(self.x, self.y, self.width, self.height)
and exceptions

class Oval(Shape):
Object-oriented programming concepts
def __init__(self, x, y, width, height, color=None, fill=0):
Shape.__init__(self,
x, y, width, height, color, fill)
File input/output
Python's intrinsic functions
def draw_filled(self,graphics):
graphics.fillOval(self.x, self.y, self.width, self.height)
Formatting, parsing, and manipulating strings

def draw_outline(self,graphics):
Interfacing with the Java APIs and working
with Java
Streams
graphics.drawOval(self.x,
self.y,
self.width,
self.height)
The Shapes Class

Using Python and Java Swing to create GUIs

Working with SQL and JDBC(TM)


TheShapes class (note the plural) holds many shapes and, like Rectangle and Oval, subclasses Shape.
Python
and Java
appletswhich when overridden iterates through the list of shapes in the
Shapes overrides only the
paint()
method,
Shapes instance and calls each one of their paint() methods. Also, Shapes calls a getRect()
In the
addition,
book
contains
instructions
forshapes
downloading
and installing the Python
method that calculates
union the
of all
of the
bounds
of all of the
it contains.
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
numerous code samples make this book a useful learning experience.
Here's the Shapesand
class:
you are a sophisticated computer user new to programming or a serious
class Shapes Whether
(Shape):
application developer, Python Programming with the Java(TM) Class Libraries will
def __init__(self):
give
you insight into the power of Python and the know-how to put it to work.
self.__shapes=[]

def addShape(self, shape):


self.__shapes.append(shape)

777

def paint(self,
graphics):
Python Programming
with the Java Class Libraries: A Tutorial for Building
for
inApplications
self.__shapes:
Web
andshape
Enterprise
with Jython
shape.paint(graphics)
By Richard Hightower

def getRect(self):
Publisher: Addison Wesley
# Lists
Pub Date: June
28, 2002to hold x,y, height and width
#
from
shape in shapes
ISBN: 0-201-61616-5
Table of
xl,yl,wl,hl
=
[],[],[],[]
Pages: 640
Contents

Iterate
through
the list
gathering
eachhasshapes
Characterized #
by ease
of use, richness
of expression,
and concise
syntax, Python
#
bounding
rectangle
remained a premier programming language for more than a decade, and is used by
for and
shape
in shapes:
novices
professionals
alike. In particular, its close relationship to Java(TM) makes
x,y,width,
= ideal
shape.getRect()
the two languages,
when used inheight
combination,
for Web and distributed enterprise
xl.append(x)
application development.
yl.append(y)

wl.append(width)
This tutorial begins
with coverage of some of the basics of Python programming. Using
hl.append(height)
plenty of skill-building
exercises and interactive programming sessions, this book will
and return
the bounding
help those new#toCalculate
programming develop
an understanding
of concepts and practical
# experienced
rectangle
for all
of the
shapes.
techniques. For
programmers,
the book
demonstrates
Python's breadth of
returnand
min(xl),
min(yl),
capabilities
shows the ways
that Python max(wl),
interfaces withmax(hl)
Java APIs for professional
application development.
Testing

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise
Applications
withneed
Jython
coversa unit
important
topics
as:
Before we start building
the graphical
interface, we
to create
level test
for such
this module
to test the
classes defined in Shape. It's much easier to debug the classes in static than in interactive mode. We also need
scaffolding code to test the module. (Our scaffolding code adds three shapes to the TestPanel class.)
Fundamental programming concepts, including statements, expressions,
and compilers
# This is interpreters,
for testing
only

if __name__ == '__main__':
Python basics, including operators, string formatting, namespaces, classes, errors,
from javax.swing
import JFrame, JPanel
and exceptions
from java.awt import Color, Font
Object-oriented programming concepts

class TestPanel(JPanel):
File input/output

def __init__(self):
Python's
intrinsic functions
self.background=Color.white
Formatting, parsing, and manipulating strings
def addShape(self,shape):
self.shapes.addShape(shape)

Interfacing with the Java APIs and working with Java Streams

def __init__(self):
Using Python and Java Swing to create GUIs
self.shapes = Shapes()
self.addShape(Rectangle(0,0,100,100,Color.blue,
1))
Working
with SQL and JDBC(TM)
self.addShape(Rectangle(100,0,100,100,Color.blue))
self.addShape(Oval(0,100,100,100,Color.blue,1))
Python
and Java applets
self.addShape(Oval(100,100,100,100, Color.blue))
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
def paint(self,graphics):
and numerous
code samples make this book a useful learning experience.
self.shapes.paint()(graphics)
Whether you are
a sophisticated
computer user new to programming
or a serious
frame = JFrame("Test
Shapes",
size=(400,440),
visible=1)
application
developer,
Python
Programming
with
the
Java(TM)
Class
Libraries will
pane = TestPanel()
give
you
insight
into
the
power
of
Python
and
the
know-how
to
put
it
to
work.
frame.contentPane = pane
frame.validate()

777

After every major change to the Shapes module, you'll want to update the scaffolding code, if necessary, and
retest.

Python Programming with the Java Class Libraries: A Tutorial for Building

Phase 1: DrawShapes
Web and Enterprise Applications with Jython
By Richard Hightower

TheDrawShapes module does the actual shape drawing. It defines classes to work with mouse and key events,
shows the status of operations,
setsAddison
a shape's
fill attribute, and sets up components that allow the user to select
Publisher:
Wesley
rectangles or ovals.
Pub Date: June 28, 2002
ISBN: 0-201-61616-5

Table ofdefines four classes:


DrawShapes

Pages: 640
Contents

Characterized
ease in
of ause,
richness of expression, and concise syntax, Python has
ShapeButton
draws aby
shape
button

remained a premier programming language for more than a decade, and is used by
and professionals
alike. In particular,
its close relationship to Java(TM) makes
ToolBoxnovices
holds components;
has a preferred
size
the two languages, when used in combination, ideal for Web and distributed enterprise
StatusBoxapplication
displaysdevelopment.
the status of a drawing operation

PaintBox
displays
usercoverage
has drawn
This
tutorialshapes
beginsthe
with
of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will

DrawShapes
those
as thenew
usertointerface
frame,develop
containsanallunderstanding
of the above of concepts and practical
help
programming
techniques. For experienced programmers, the book demonstrates Python's breadth of
Shapes Button capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
ShapeButton represents a particular shape and extends javax.swing.JButton. It's passed a Shape
Python
withpaint()
the Java(TM)
Class ItLibraries:
A Tutorial
for Building
Webheight
instance and draws the
shapeProgramming
in its overridden
method.
also defines
the preferred
width and
and
Enterprise
Applications
with
Jython
covers
important
topics
such
as:
for the button.

class ShapeButton(JButton):
Fundamental programming
def __init__(self,
shape): concepts, including statements, expressions,
interpreters, and
self.shape
= compilers
shape
Python basics, including operators, string formatting, namespaces, classes, errors,

def paint(self, graphics):


and exceptions
JButton.paint()(self, graphics)
self.shape.paint()(graphics)
Object-oriented programming concepts
def getPreferredSize(self):
File input/output
d = Dimension(30,30)
return
Python'sdintrinsic functions
Formatting, parsing, and manipulating strings

ToolBox

Interfacing with the Java APIs and working with Java Streams

ToolBox holds ShapeButton and extends javax.swing.Jpanel. It doesn't do much besides


define a preferred size.

Using Python and Java Swing to create GUIs

class ToolBox (JPanel):


Working with SQL and JDBC(TM)
def __init__(self):
JPanel.__init__(self)
Python and Java applets
In addition, the book contains instructions for downloading and installing the Python
def getPreferredSize(self):
language
and the Java Development
d = Dimension(40,
0) Kit (JDK). Terminology, definitions, explanations,
andreturn
numerousdcode samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
you insight
into
power
Python
and javax.swing.JPanel
the know-how to put it to work.
StatusBox holdsgive
the current
status
of the
events
andofalso
extends
. As a helper
StatusBox

class, it displays the current status of the drawing options, such as the x,y position of the mouse pointer and the
shape being drawn.

777

class StatusBox (JPanel):

def __init__(self):
Python Programming with the Java Class Libraries: A Tutorial for Building
JPanel.__init__(self)
Web
and Enterprise Applications with Jython
self.coordinates
= JTextField(15, editable=0)
By Richard
Hightower
self.format = 'x = %d, y = %d'
self.add(self.coordinates)
Publisher: Addison Wesley
Pub Date: June 28, 2002

Table of
Contents

self.event_type
ISBN: 0-201-61616-5= JLabel ('MOUSE STATUS ')
self.add(self.event_type)
Pages: 640
self.shape_type = JLabel ('SHAPE STATUS ')
self.add(self.shape_type)
Characterized
by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by

def setXY(self,
x,y): alike. In particular, its close relationship to Java(TM) makes
novices and professionals
= self.format
% (x,y,)
theself.coordinates.text
two languages, when used in combination,
ideal for Web and
distributed enterprise
application development.

def setMouseDrag(self, x, y):


self.event_type.text
'MOUSE
DRAG
'
This
tutorial begins with coverage of =
some
of the basics
of Python
programming. Using
self.setXY(x,y)
plenty
of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical

def setMouseMove(self,
x, y):
techniques. For experienced programmers,
the book demonstrates Python's breadth of
self.event_type.text
= 'MOUSE
MOVE
' APIs for professional
capabilities
and shows the ways that Python
interfaces
with Java
self.setXY(x,y)
application development.
Python Programming with the x,
Java(TM)
def setMousePress(self,
y): Class Libraries: A Tutorial for Building Web
andself.event_type.text
Enterprise Applications with Jython
covers important
topics
= 'MOUSE
PRESS
' such as:
self.setXY(x,y)
Fundamental programming x,
concepts,
def setMouseRelease(self,
y): including statements, expressions,
interpreters, and compilers
self.event_type.text
= 'MOUSE RELEASE '
self.setXY(x,y)
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions

def setShapeType(self, shape_type):


Object-oriented programming concepts

# Set the label based on the shape type


if File
shape_type
input/output == PaintBox.RECTANGLE:
self.shape_type.text = 'RECTANGLE'
Python's intrinsic functions

elif shape_type == PaintBox.OVAL:


Formatting,
parsing, and manipulating strings
self.shape_type.text
= 'OVAL'
PaintBox

Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs

PaintBox performs all of the graphics operations and handles the mouse events (later it will handle the key
Working
withsample
SQL and
JDBC(TM)
events). It's the bread and butter
of this
application,
the center ring in this three-ring circus.
Python
andinJava
applets
When the user hits the mouse
button
the paint
box, the shape drawing begins. As he drags the lower corner of
the shape, an outline appears (this is called rubberbanding). When he lets go of the mouse, the shape is created,
In addition,
the book
contains
instructions
for downloading
and
installing the Python
added to the other shapes,
and redrawn
when
PaintBox
'spaint()
method is
called.
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
PaintBox extendsand
JComponent
can draw
either
or ovals
and has
four attributes that
numerous code. Itsamples
make
thisrectangles
book a useful
learning
experience.
determine how the current shape will be drawn: color, fill, rectangle, and oval. The constructor defines these
are a sophisticated
computer user ,new
to programming
or a serious , and
attributes and sets upWhether
the eventyou
handlers
for the mouseDragged
mouseMoved
,mousePressed
with the
Java(TM) Class
Libraries
mouseReleasedapplication
events. It'sdeveloper,
passed an Python
instanceProgramming
of StatusBox
(status)
, which
it uses towill
show the
give
you
insight
into
the
power
of
Python
and
the
know-how
to
put
it
to
work.
status of the drawing operations.
Here's the PaintBox constructor:

777

class PaintBox (JComponent):

RECTANGLE=1
Python Programming with the Java Class Libraries: A Tutorial for Building
OVAL=2Web and Enterprise Applications with Jython
By Richard Hightower

def __init__(self, status):


JComponent.__init__(self)
Publisher: Addison Wesley
self.opaque=1
Pub Date:
June 28, 2002
self.background=Color.white
ISBN:
0-201-61616-5
Table of
self.status
= status
Pages: 640
Contents
self.shapes = Shapes()
self.shape_type
PaintBox.RECTANGLE
Characterized
by ease of use,=richness
of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
self.mouseDragged
= particular,
self.handle_mouseDragged
novices
and professionals alike. In
its close relationship to Java(TM) makes
theself.mouseMoved
two languages, when used=inself.handle_mouseMoved
combination, ideal for Web and distributed enterprise
self.mousePressed
= self.handle_mousePress
application
development.

self.mouseReleased = self.handle_mouseRelease

This tutorial begins with coverage of some of the basics of Python programming. Using
self.fill=0
plenty
of skill-building exercises and interactive programming sessions, this book will
self.color=Color.red
help
those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
The drawing mechanism
starts off
thethe
user
clicks
mouseinterfaces
button, which
firesAPIs
the for professional
capabilities
andwhen
shows
ways
thatthe
Python
with Java
handle_mousePress
method.
The
event
handler
sets
the
shape's
starting
point
(
start) and initializes its
application development.
ending point (last) to that value.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
def handle_mousePress(self,
event):
and Enterprise Applications
with Jython covers important topics such as:

# Print the status


Fundamental programming concepts, including
statements, expressions,
self.status.setMousePress(event.x,
event.y)
interpreters, and compilers

# Save the initial location.


basics, including
string formatting, namespaces, classes, errors,
# InPython
addition
save operators,
the initial
and
exceptions
# location as the last.
self.last = self.start = event.point
Object-oriented programming concepts

As the user drags the mouse, she gets visual feedback via rubberbanding. When called, the event handler for
input/output
mouseDragged draws File
an outline
of the shape and sets the last point to the current point. Then it calls
drawRubberShape()Python's
twice, once with the last point and once with the current point.
intrinsic functions

def handle_mouseDragged(self,event):
Formatting, parsing, and manipulating strings
# Print
thewith
status.
Interfacing
the Java APIs and working with Java Streams
self.status.setMouseDrag(event.x, event.y)
Using Python and Java Swing to create GUIs

# Erase the old rubberband shape at the


Working
with SQL and
JDBC(TM)
# old
location.
Create
the new rubberband shape
# at the new location
Python and Java applets
self.drawRubberShape(self.last.x,
self.last.y)
self.drawRubberShape(event.x, event.y)
In addition, the book contains instructions for downloading and installing the Python
# Save the current event.x and
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
# event.y as the last.
and numerous code samples make this book a useful learning experience.
self.last = event.point
Whether you are a sophisticated computer user new to programming or a serious

drawRubberShape() is smart enough to erase the last shape drawn whenever it's called twice with the
application developer, Python Programming with the Java(TM) Class Libraries will
same point. It does this with the setXORMode() method of the java.awt.Graphics class instance,
give you insight into the power of Python and the know-how to put it to work.
which sets the graphic mode to XOR.XOR sees to it that a line drawn more than once will be erased. Essentially,
it ensures that the colors of the graphics are those specifed in setXORMode() for the current graphic context.

777

Notice that we dispose of the graphic when we're done with it, using a finally block. After
drawRubberShape() sets the graphics mode, it calculates the shape's width and height and then calls the

__drawShape()Python
method,
which actuallywith
draws
theJava
shape Class
in the Libraries:
current mode.
Programming
the
A Tutorial for Building
Web and Enterprise Applications with Jython

def drawRubberShape(self,
By Richard Hightower x, y):
g = self.graphics
Publisher: Addison Wesley

Table of
Contents

try:

# Pub
Set
the graphics to XOR mode,
Date: June 28, 2002
# which allows rubberbanding.
ISBN: 0-201-61616-5
# Calculate the width and height.
Pages: 640
# Draw the outline of the shape.
Characterized by ease of use, richness of expression, and concise syntax, Python has
g.setXORMode(self.background)
remained a premier programming language for more than a decade, and is used by
width = abs(self.start.x - x)
novices and professionals alike. In particular, its close relationship to Java(TM) makes
height = abs(self.start.y - y)
the two languages, when used in combination, ideal for Web and distributed enterprise
self.__drawShape(g, self.start.x, self.start.y, width, height)
application development.

finally:
g.dispose()
This
tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will

__drawShape() checks for the shape it's supposed to drawrectangle or oval. It then creates the specified
help those new to programming develop an understanding of concepts and practical
shape and uses it to draw the corresponding shape, which in turn calls drawOval() or drawRect()
techniques. For experienced programmers, the book demonstrates Python's breadth of
accordingly. The x and y of __drawShape correspond to the starting point defined in the event handler for
capabilities and shows the ways that Python interfaces with Java APIs for professional
themousePress event. The width and height are the width and height as calculated from the last or current
application development.
point in the mouseDrag event handler.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web

def __drawShape(self, g, x, y, width, height):


and Enterprise Applications with Jython covers important topics such as:
if self.shape_type == PaintBox.RECTANGLE:
rect=Rectangle(self.start.x,self.start.y, width,height,fill=0)
rect.paint(g)
Fundamental programming concepts, including statements, expressions,
if self.shape_type
==compilers
PaintBox.OVAL:
interpreters, and
oval = Oval(self.start.x, self.start.y, width, height, fill=0)
Python basics, including operators, string formatting, namespaces, classes, errors,
oval.paint()(g)
and exceptions
When the user lets go of the mouse, the mouseRelease event is fired. The handler for this event is
Object-oriented
programming
concepts
handle_mouseRelease
, which calculates
the width
and height of the shape and then creates a
corresponding rectangle or oval.
File input/output
The shape's x,y coordinates are the starting point obtained during the handling of the mousePress event. Its
Python's
intrinsic
functions
width and height are the distance
from
the starting
point at which the mouseRelease event handler is
invoked (that is, when the user releases the mouse button). The shape is then added to the shapes attribute.
parsing,
and
The panel's repaint()Formatting,
method is called
with
themanipulating
boundary of strings
the shape so that the shape is drawn with the
paint() method.
Interfacing with the Java APIs and working with Java Streams

def handle_mouseRelease(self,
event):
Using Python and Java Swing to create GUIs
# Print
Workingthe
with status
SQL and JDBC(TM)
self.status.setMouseRelease(event.x, event.y)
Python and Java applets

# Calculate the width and the height


the book contains instructions
for downloading and installing the Python
width =In addition,
abs(self.start.x
- event.x)
and the Java Development
Kit (JDK). Terminology, definitions, explanations,
height language
= abs(self.start.y
- event.y)
and numerous code samples make this book a useful learning experience.

shape = None #to hold the shape we are about to create


Whether you are a sophisticated computer user new to programming or a serious
application
developer,
Python Programming
the Java(TM)
Libraries
will
# Create
the shape
based onwith
the
currentClass
shape
type.
give
you
insight
into
the
power
of
Python
and
the
know-how
to
put
it
to
work.
# Then add the shape to self.shapes.

if self.shape_type == PaintBox.RECTANGLE:

777

shape = Rectangle(self.start.x, self.start.y, width, height,


self.color, self.fill)

Python Programming with the Java Class Libraries: A Tutorial for Building

elif self.shape_type
== PaintBox.OVAL:
Web and Enterprise Applications
with Jython
shape
=
Oval(self.start.x,
self.start.y, width, height,
By Richard Hightower
self.color, self.fill)
Publisher: Addison Wesley

if not shape
is None:
Pub Date: June 28, 2002
self.shapes.addShape(shape)
ISBN: 0-201-61616-5
x,y,width,height = shape.getRect()
Table of
Pages: 640
Contents
self.repaint(x,y,width+1, height+1)

Characterized
by ease of use, richness
of expression,
and concise
syntax,
Pythonlisthas
Thepaint() method
calls the shapes.paint()
method,
which iterates
through
the shapes
and calls
remained
a
premier
programming
language
for
more
than
a
decade,
and
is
used by
all of the shapes' paint() methods.
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two graphics):
languages, when used in combination, ideal for Web and distributed enterprise
def paint (self,
application
development.
...

...

This#Draw
tutorial begins
of some of the basics of Python programming. Using
all with
of coverage
the shapes.
plenty
of
skill-building
exercises
and
self.shapes.paint(graphics) interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
For experienced
thePaintBox
book demonstrates
Python's
breadthmethods
of
Since the selection oftechniques.
shape attributes
happens programmers,
in another class,
exposes
the following
capabilities
and
shows
the
ways
that
Python
interfaces
with
Java
APIs
for
professional
so that the attributes can be set by the class that contains a PaintBox instance:
application development.

setShapeType()
sets the current
shape
type Class Libraries: A Tutorial for Building Web
Python Programming
with the
Java(TM)
and Enterprise Applications with Jython covers important topics such as:

setFill() turns the shape fill property on or off


setShapeColor()
sets the
current colorconcepts,
of the shape
to be drawn
Fundamental
programming
including
statements, expressions,
def setShapeType(self,
shape_type):
interpreters, and compilers
self.status.setShapeType(shape_type)
Python basics, including
operators, string formatting, namespaces, classes, errors,
self.shape_type
= shape_type
and exceptions

def getShapeType(self):
programming concepts
returnObject-oriented
shape_type
File input/output

def setFill(self, value):


self.fill
value
Python's=intrinsic
functions
def setShapeColor(self,
Formatting, parsing,color):
and manipulating strings
self.color = color
Interfacing with the Java APIs and working with Java Streams
DrawShapes

Using Python and Java Swing to create GUIs

As the parent frame for the drawing application, DrawShapes contains StatusBox,ToolBox, and
Working with SQL and JDBC(TM)
PaintBox instances. It also handles all of the options for the shapes and allows the user to pick different
shapes as represented by ShapeButton
in the ToolBox instance.
Python and Java applets
TheDrawShapesIn
constructor
creates
panels,
optionsfor(an
instance of and
Panel
),toolbar
(an
addition, the
bookfour
contains
instructions
downloading
installing
the Python
instance of Panel),language
statusand
(anthe
instance
of
StatusBox
),
and
paint
(an
instance
of
PaintBox
). The
Java Development Kit (JDK). Terminology, definitions, explanations,
paint panel is added
to
the
center
region
of
the
DrawShapes
frame;
the
status
panel
is
added
to
the
and numerous code samples make this book a useful learning experience.
south region.
Whether you are a sophisticated computer user new to programming or a serious
class DrawShapes(JFrame):
application developer, Python Programming with the Java(TM) Class Libraries will
def __init__(self):
give you insight into the power of Python and the know-how to put it to work.

JFrame.__init__(self,title='Draw Shapes',visible=1,size=(400,400))
self.__init__toolbar()
self.__init__options()

777

self.statusPane
StatusBox()
Python Programming =
with
the Java Class Libraries: A Tutorial for Building
self.contentPane.add(self.statusPane,
BorderLayout.SOUTH)
Web and Enterprise Applications with Jython
self.PaintPane
By Richard Hightower = PaintBox(self.statusPane)
self.contentPane.add(self.PaintPane, BorderLayout.CENTER)
...
...

Publisher: Addison Wesley


Pub Date: June 28, 2002
ISBN: 0-201-61616-5

The constructor
Table of also calls __init__toolbar and __init__option , which create the toolbar

Pages: 640
Contentspanels, respectively.
andoption

Characterized
byshape
ease of
use, richness
of them
expression,
and concise
has is
__init__toolbar
creates two
buttons
and adds
to the toolbar
pane. syntax,
One ofPython
the buttons
remained
a
premier
programming
language
for
more
than
a
decade,
and
is
used
by
initialized with an instance of the Rectangle class; the other, with an instance of the Oval class. The
novices
and professionals
alike.
In particular,
its close
relationship
to Java(TM)
makes
ShapeButton class
represents
changing the
drawing
mode to either
rectangle
or oval.
Its handlers
are set to
the
two
languages,
when
used
in
combination,
ideal
for
Web
and
distributed
enterprise
therect_pressed() and oval_pressed() methods, which change the shape to an oval or a
rectangle.

application development.

This also
tutorial
begins
with coverage
oftosome
of theregion
basicsofofthe
Python
programming.
Using
__init__toolbar
adds
the toolbar
panel
the west
DrawShapes
frame
and is
defined as follows: plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
def __init__toolbar(self):
capabilities
and shows the ways that Python interfaces with Java APIs for professional
toolbar
= ToolBox()
application development.

# Add the rectangle button to the toolbar


Programming with the Java(TM) Class
A Tutorial for Building Web
rect =Python
ShapeButton(Rectangle(4,
4, Libraries:
20, 20))
and
Enterprise
Applications
with
Jython
covers
important
topics
such as:
toolbar.add(rect)
rect.actionPerformed = self.rect_pressed
Fundamental programming concepts, including statements, expressions,

# Add
the oval
button to the toolbar
interpreters,
and compilers
oval = ShapeButton(Oval(4, 4, 10, 20))
toolbar.add(oval)
Python basics, including operators, string formatting, namespaces, classes, errors,
oval.actionPerformed
= self.oval_pressed
and exceptions
Object-oriented BorderLayout.WEST)
programming concepts
self.add(toolbar,
Filethe
input/output
__init__options does
equivalent for the options pane. It creates a choice component for color
and a checkbox component fill/no fill. It then adds these components to the options pane and places the pane in
Python's intrinsic
functions
the north region of the DrawShapes
frame.

Formatting, parsing, and manipulating strings


def __init__options(self):
optionsPane = Panel()

Interfacing with the Java APIs and working with Java Streams

# Set
up the checkbox item for the fill option
Using Python and Java Swing to create GUIs
check = Checkbox('Fill')
optionsPane.add(check)
Working with SQL and JDBC(TM)
check.itemStateChanged = self.fill_clicked
Python and Java applets

# Set up the choice for color


the book contains instructions for downloading and installing the Python
colorsIn addition,
= Choice()
language and the Java
Development Kit (JDK). Terminology, definitions, explanations,
self.colors_dict
= {'blue':Color.blue,
and numerous code'green':Color.green,
samples make this book a useful learning experience.
'red':Color.red,
Whether you are a sophisticated
computer user new to programming or a serious
'yellow':Color.yellow,
application developer,
Python
Programming
with the Java(TM) Class Libraries will
'orange':Color.orange,
give you insight into'cyan':Color.cyan,
the power of Python and the know-how to put it to work.
'pink':Color.pink,
'gray':Color.gray
}
for color in self.colors_dict.keys():

777

colors.add(color)
Python
Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
optionsPane.add(colors)
By Richard Hightower
colors.itemStateChanged = self.color_changed
self.add(optionsPane,
BorderLayout.NORTH)
Publisher: Addison Wesley
Pub Date: June 28, 2002

DrawShapes Event Handler


ISBN: 0-201-61616-5

Table of
Contents

Pages: 640

All of the event handlers for the components added to the options and toolbar panes correspond to
setting properties in Characterized
the paint pane
(PaintBox
instance).
by ease
of use, richness
of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
Therect_pressed event handler is called when the rectangle button is pressed; it sets the shape type
the two languages, when used in combination, ideal for Web and distributed enterprise
of the paint pane to PaintBox .RECTANGLE.
application development.
Theoval_pressed event handler is called when the oval button is pressed; it sets the shape type of
This tutorial begins with coverage of some of the basics of Python programming. Using
thepaint pane to PaintBox.OVAL.
plenty of skill-building exercises and interactive programming sessions, this book will
help thoseevent
new tohandler
programming
anuser
understanding
of concepts
Thefill_clicked
is calleddevelop
when the
checks or unchecks
theand
fill practical
checkbox. If the
techniques.
For
experienced
programmers,
the
book
demonstrates
Python's
breadth of
box is unchecked, the paint pane fill property is set to false. If the box is checked, the paint
pane
capabilities
and
shows
the
ways
that
Python
interfaces
with
Java
APIs
for
professional
property is set to true.
application development.
Thecolor_changed event handler is called when the user selects a new color in the choice box; it
Python
Programming
with
the Java(TM)
Class
sets the color of
the paint
box's current
paint
mode to the
colorLibraries:
selected. A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
These event handlers are defined as follows:

Fundamental
programming concepts, including statements, expressions,
def rect_pressed(self,
event):
interpreters, and compilers
self.paintPane.setShapeType(PaintBox.RECTANGLE)
Python basics, including operators, string formatting, namespaces, classes, errors,

def oval_pressed(self, event):


and exceptions
self.paintPane.setShapeType(PaintBox.OVAL)
Object-oriented programming concepts

def fill_clicked(self, event):


if(event.stateChange==ItemEvent.SELECTED):
File input/output
self.PaintPane.setFill(1)
Python's intrinsic functions
elif (event.stateChange==ItemEvent.DESELECTED):
self.PaintPane.setFill(0)
Formatting, parsing, and manipulating strings

def color_changed(self,event):
with the Java APIs and working with Java Streams
colorname =Interfacing
event.item
color = self.colors_dict[colorname]
Using Python and Java Swing to create GUIs
self.PaintPane.setShapeColor(color)
Working with SQL and JDBC(TM)

The Complete Shapes


and DrawShapes Modules
Python and Java applets
We've covered all ofIntheaddition,
classes. the
At this
you instructions
may want tofor
rundownloading
the Shapes and
bookpoint,
contains
andDrawShapes
installing themodules
Python to see
the drawing packagelanguage
in action.and
Here's
the Shapes
module.Kit (JDK). Terminology, definitions, explanations,
the Java
Development
and numerous code samples make this book a useful learning experience.

class Shape:
def __init__(self,
x, y, width=0,
color=None,
Whether you are a sophisticated
computer user height=0,
new to programming
or a serious fill=0):
self.x=x
application developer, Python Programming with the Java(TM) Class Libraries will
self.y=y
give
you insight into the power of Python and the know-how to put it to work.
self.width=width
self.height=height
self.color=color
self.fill=fill

777

Python Programming
with the Java Class Libraries: A Tutorial for Building
def paint(self,
graphics):
Web and Enterprise Applications with Jython
By
Richard
if
notHightower
self.color is None:

oldcolor = graphics.foregroundColor
= self.color

Publisher:graphics.color
Addison Wesley
Pub Date: June 28, 2002

Table of
Contents

ISBN: 0-201-61616-5
if self.fill:
Pages:self.draw_filled(graphics)
640
else:
Characterized
by ease of use, richness of expression, and concise syntax, Python has
self.draw_outline(graphics)

remained a premier programming language for more than a decade, and is used by
novices
and professionals
alike.is
In particular,
if not
self.color
None: its close relationship to Java(TM) makes
the two languages,
when
used
in
combination,
ideal for Web and distributed enterprise
graphics.color = oldcolor
application development.

def draw_filled(self, graphics):


This
tutorial begins with coverage of some of the basics of Python programming. Using
pass
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming
develop an understanding of concepts and practical
def draw_outline(self,
graphics):
techniques.
For
experienced
programmers,
the book demonstrates Python's breadth of
pass
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
def getRect(self):

return self.x, self.y, self.width, self.height

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
class Rectangle(Shape):

def __init__(self, x, y, width, height, color=None, fill=0):


Shape.__init__(self,
x, y, including
width,statements,
height,
color, fill)
Fundamental programming concepts,
expressions,
interpreters, and compilers

def draw_filled(self,graphics):
graphics.fillRect(self.x,
self.y,
self.width,
self.height)
Python basics, including operators, string
formatting,
namespaces, classes,
errors,
and exceptions

def draw_outline(self,graphics):
Object-oriented programming concepts
graphics.drawRect(self.x,
self.y, self.width, self.height)
File input/output
class Oval(Shape):
def __init__(self, x, y, width, height, color=None, fill=0):
Python's intrinsic functions
Shape.__init__(self, x, y, width, height, color, fill)
Formatting, parsing, and manipulating strings

def draw_filled(self,graphics):
graphics.fillOval(self.x,
self.y,
self.width,
self.height)
Interfacing with the Java APIs and working
with Java
Streams
def draw_outline(self,graphics):
Using Python and Java Swing to create GUIs
graphics.drawOval(self.x, self.y, self.width, self.height)
Working with SQL and JDBC(TM)

class Shapes (Shape):


Python and Java applets
def __init__(self):
self.__shapes=[]

In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
def addShape(self, shape):
and numerous code samples make this book a useful learning experience.

self.__shapes.append(shape)

Whether you are a sophisticated computer user new to programming or a serious

def paint(self,
graphics):
application developer,
Python Programming with the Java(TM) Class Libraries will
for
shape
in the
self.__shapes:
give you insight into
power of Python and the know-how to put it to work.
shape.paint()(graphics)

777

def getRect(self):
# Lists to hold x,y,height and width from shape in shapes

xl,yl,wl,hl
= [],[],[],[]
Python Programming
with the Java
Class Libraries: A Tutorial for Building
# Iterate
through
list gathering each shapes
Web and Enterprise
Applications
with the
Jython
# bounding rectangle
By Richard Hightower

Table of
Contents

for shape in shapes:


Publisher:x,y,width,
Addison Wesley height = shape.getRect()
xl.append(x)
Pub Date: June 28, 2002
ISBN:yl.append(y)
0-201-61616-5
wl.append(width)
Pages: 640
hl.append(height)

Characterized by ease of use, richness of expression, and concise syntax, Python has
returna premier
min(xl),
min(yl),
remained
programming
languagemax(wl),
for more thanmax(hl)
a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
# Thistheis
testing
only
two for
languages,
when used
in combination, ideal for Web and distributed enterprise
if __name__ ==
'__main__':
application
development.

from javax.swing import JFrame, JPanel


from java.awt
import
Color,of Font
This tutorial begins
with coverage
some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will

class help
TestPanel(JPanel):
those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
def __init__(self):
capabilities
and shows the ways that Python interfaces with Java APIs for professional
self.background=Color.white
application development.
Python
with the Java(TM) Class Libraries: A Tutorial for Building Web
def Programming
addShape(self,shape):
and Enterprise Applications
with Jython covers important topics such as:
self.shapes.addShape(shape)

def __init__(self):
Fundamental programming
concepts,
including statements, expressions,
self.shapes
= Shapes()
interpreters, and
compilers
self.addShape(
Rectangle( 0, 0, 100, 100,
Color.blue,
1))
Python basics, including operators, string formatting, namespaces, classes, errors,
self.addShape(
Rectangle(100,
0, 100, 100,
and exceptions
Color.blue))
Object-orientedself.addShape(
programming conceptsOval( 0, 100, 100, 100, Color.blue,
1))
self.addShape( Oval(100, 100, 100, 100, Color.blue))
File input/output
intrinsic functions
def Python's
paint(self,graphics):
self.shapes.paint(graphics)
Formatting, parsing, and manipulating strings

frame = JFrame("Test Shapes", size=(400,440), visible=1)


Interfacing with the Java APIs and working with Java Streams
pane = TestPanel()
frame.contentPane
= pane
Using Python and
Java Swing to create GUIs
frame.validate()
Working with SQL and JDBC(TM)
Here's the DrawShapes module:
Python and Java applets

from
from
from
from
from

Shapes import *
java.awtIn addition,
importtheFont,
Color,
Dimension,
BorderLayout
book contains
instructions
for downloading
and installing the Python
javax.swing
import
JComboBox,
JLabel,
JTextField,
JComponent
language and the Java Development Kit (JDK). Terminology, definitions,
explanations,
javax.swing
import
BoxLayout,
JCheckBox,
JButton,
JFrame, JPanel
and numerous code samples make this book a useful learning experience.
java.awt.event import KeyEvent, ItemEvent
Whether you are a sophisticated computer user new to programming or a serious

class ShapeButton(JButton):
application developer, Python Programming with the Java(TM) Class Libraries will
def __init__(self,
shape):
give you insight into the
power of Python and the know-how to put it to work.
self.shape = shape

777

def paint(self, graphics):


JButton.paint(self, graphics)

def

self.shape.paint(graphics)
Python
Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
getPreferredSize(self):
By Richard Hightower
d = Dimension(30,30)
return
d
Publisher: Addison
Wesley
Pub Date: June 28, 2002

class ToolBox (JPanel):


ISBN: 0-201-61616-5
Table def
of
__init__(self):

Pages: 640
Contents
JPanel.__init__(self)
Characterized by ease of use, richness of expression, and concise syntax, Python has

def getPreferredSize(self):
remained a premier programming language for more than a decade, and is used by
d = and
Dimension(40,
0)particular, its close relationship to Java(TM) makes
novices
professionals alike. In
d when used in combination, ideal for Web and distributed enterprise
thereturn
two languages,
application development.

class StatusBox (JPanel):


def __init__(self):
This tutorial begins with coverage of some of the basics of Python programming. Using
JPanel.__init__(self)
plenty
of skill-building exercises and interactive programming sessions, this book will
self.coordinates
JTextField(15,
help
those new to programming= develop
an understanding editable=0)
of concepts and practical
self.format
= 'xprogrammers,
= %d, y the
= book
%d' demonstrates Python's breadth of
techniques.
For experienced
self.add(self.coordinates)
capabilities
and shows the ways that Python interfaces with Java APIs for professional
application development.

self.event_type = JLabel ('MOUSE STATUS ')


Python
Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
self.add(self.event_type)
andself.shape_type
Enterprise Applications with
Jython covers
importantSTATUS
topics such')
as:
= JLabel
('SHAPE

self.add(self.shape_type)
Fundamental
programming concepts, including statements, expressions,
def setXY(self,
x,y):
interpreters, and compilers
self.coordinates.text
= self.format % (x,y,)
Python basics, including operators, string formatting, namespaces, classes, errors,

def setMouseDrag(self,
x, y):
and exceptions
self.event_type.text = 'MOUSE DRAG '
self.setXY(x,y)
Object-oriented programming concepts
def setMouseMove(self,
x, y):
File input/output
self.event_type.text = 'MOUSE MOVE '
Python's intrinsic functions
self.setXY(x,y)

Formatting, parsing, andx,


manipulating
strings
def setMousePress(self,
y):
self.event_type.text = 'MOUSE PRESS '
Interfacing with the Java APIs and working with Java Streams
self.setXY(x,y)
Using Python and Java Swing to create GUIs

def setMouseRelease(self, x, y):


self.event_type.text
= 'MOUSE RELEASE '
Working with SQL and JDBC(TM)
self.setXY(x,y)
Python and Java applets

def setShapeType(self, shape_type):


In addition, the book contains instructions for downloading and installing the Python
language and#theSet
Java the
Development
(JDK). Terminology,
definitions,
explanations,
labelKitbased
on the shape
type
andif
numerous
code
samples
make
this
book
a
useful
learning
experience.
shape_type == PaintBox.RECTANGLE:

self.shape_type.text = 'RECTANGLE'

Whether you are a sophisticated computer user new to programming or a serious


application
developer, Python==
Programming
with the Java(TM) Class Libraries will
elif shape_type
PaintBox.OVAL:
give you insight
into
the
power
of
Python
and
self.shape_type.text the
= know-how
'OVAL' to put it to work.

777

class PaintBox (JComponent):


RECTANGLE=1
OVAL=2

Python Programming with the Java Class Libraries: A Tutorial for Building

def __init__(self,
status): with Jython
Web and Enterprise Applications
JComponent.__init__(self)
By Richard Hightower
self.opaque=1
self.background=Color.white
Publisher:
Addison Wesley
self.status
= status
Pub Date: June 28, 2002
self.shapes
= Shapes()
ISBN: 0-201-61616-5
Table of
self.shape_type = PaintBox.RECTANGLE
Pages: 640
Contents
self.mouseDragged = self.handle_mouseDragged
self.mouseMoved = self.handle_mouseMoved
Characterized by ease of use, richness of expression, and concise syntax, Python has
self.mousePressed = self.handle_mousePress
remained a premier programming language for more than a decade, and is used by
self.mouseReleased = self.handle_mouseRelease
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
self.fill=0
application development.

self.color=Color.red

This tutorial begins with coverage of some of the basics of Python programming. Using

def getPreferredSize(self):
plenty of skill-building exercises and interactive programming sessions, this book will
d those
= Dimension(400,400)
help
new to programming develop an understanding of concepts and practical
returnFord experienced programmers, the book demonstrates Python's breadth of
techniques.
capabilities and shows the ways that Python interfaces with Java APIs for professional

def __drawShape(self,
application development. g, x, y, width, height):

if Programming
self.shape_type
== PaintBox.RECTANGLE:
Python
with the Java(TM)
Class Libraries: A Tutorial for Building Web
rect with
= Rectangle(self.start.x,
and Enterprise Applications
Jython covers important topics such as:self.start.y, width,h

rect.paint(g)
if self.shape_type == PaintBox.OVAL:
Fundamental
concepts, including statements,
expressions,width, height,fil
oval programming
= Oval(self.start.x,
self.start.y,
interpreters,
and compilers
oval.paint()(g)
Python basics, including operators, string formatting, namespaces, classes, errors,

def drawRubberShape(self, x, y):


and exceptions
g = self.graphics

Object-oriented programming concepts

# Set the graphics to XOR mode, which allows rubberbandin

# Calculate the width and height.


File input/output
# Draw the outline of the shape.
try:
Python's intrinsic functions
g.setXORMode(self.background)
Formatting,
parsing,
and manipulating strings - x)
width
= abs(self.start.x
height = abs(self.start.y - y)
Interfacing
with the Java APIs and working
with Java Streamsself.start.y, width,
self.__drawShape(g,
self.start.x,
height)
Using Python and Java Swing to create GUIs
finally:
g.dispose()
Working
with SQL and JDBC(TM)
def handle_mousePress(self,
event):
Python and Java applets
In addition, the
contains
# book
Print
theinstructions
status for downloading and installing the Python
language and the Javaself.status.setMousePress(event.x,
Development Kit (JDK). Terminology, definitions, explanations,
event.y)
and numerous
samples
this booklocation.
a useful learning experience.
# code
Save
themake
initial

# In addition save the initial location as the last.


Whether
you are a sophisticated
computer
new to programming or a serious
self.last
= self.start
= user
event.point
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.
def handle_mouseDragged(self,event):

# Print the status.


self.status.setMouseDrag(event.x, event.y)

777

# Erase with
thetheold
rubberband
shape
at for
the
old location.
Python Programming
Java
Class Libraries:
A Tutorial
Building
# Create
the new
rubberband
shape at the new location
Web and Enterprise
Applications
with
Jython
self.drawRubberShape(self.last.x,
self.last.y)
By Richard
Hightower
self.drawRubberShape(event.x, event.y)
Publisher: Addison Wesley

Table of
Contents
def

Save
the current event.x and event.y as the last.
Pub Date:#June
28, 2002
self.last
=
event.point
ISBN: 0-201-61616-5
Pages: 640

handle_mouseMoved(self,event):

Characterized by ease of use, richness of expression, and concise syntax, Python has
# Print
the status.
remained a premier
programming
language for more than a decade, and is used by
self.status.setMouseMove(event.x,event.y)
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
def handle_mouseRelease(self,
event):
application development.

Print
the status
This tutorial #
begins
with coverage
of some of the basics of Python programming. Using
self.status.setMouseRelease(event.x,
event.y)
plenty
of skill-building exercises and interactive programming sessions,
this book will
help those new to programming develop an understanding of concepts and practical
# Calculate
the width
anddemonstrates
the height
techniques. For
experienced programmers,
the book
Python's breadth of
width and
= abs(self.start.x
event.x)
capabilities
shows the ways that Python -interfaces
with Java APIs for professional
heightdevelopment.
= abs(self.start.y - event.y)
application
Python
Programming
the hold
Java(TM)
Class
Libraries:
Tutorial
for Building
Web
shape
= Nonewith
#to
the
shape
weA are
about
to create
and Enterprise Applications with Jython covers important topics such as:

# Create the shape based on the current shape type.


# Then add the shape to self.shapes.
programming ==
concepts,
including statements, expressions,
if Fundamental
self.shape_type
PaintBox.RECTANGLE:
interpreters,
and=compilers
shape
Rectangle(self.start.x, self.start.y, width,
height, self.color, self.fill)
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions

elif self.shape_type == PaintBox.OVAL:


shape =
Oval(self.start.x,
self.start.y, width, height,
Object-oriented
programming
concepts
self.color, self.fill)
File input/output

if not shape is None:


Python's
intrinsic functions
self.shapes.addShape(shape)
x,y,width,height = shape.getRect()
Formatting,
parsing, and manipulating strings
self.repaint()(x,y,width+1,
height+1)
Interfacing with the Java APIs and working with Java Streams

def paint (self, graphics):


self.fillBackground(graphics)
Using Python and Java Swing to create GUIs
#Draw all of the shapes.
self.shapes.paint(graphics)
Working with SQL and JDBC(TM)
def fillBackground
Python and Java(self,
applets graphics):

In addition, the
bookthe
contains
instructions forcolor
downloading and installing the Python
#Get
background
language
and the Java Development Kit (JDK). Terminology, definitions, explanations,
background=self.background
and numerous
code samples
make this book a useful learning experience.
#Get
the size

size=self.getSize()

Whether
you are
a sophisticated
computer user new
to programming or a serious
width,
height
= size.width,
size.height
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight
into the power
of Python and the
know-how
to put
it to work.
# Create
a rectangle
that
is as
big

# as the whole drawing area.


rect = Rectangle(0,0, width, height, background, 1)
rect.paint(graphics)

777

def setShapeType(self,
Python Programming withshape_type):
the Java Class Libraries: A Tutorial for Building
self.status.setShapeType(shape_type)
Web
and Enterprise Applications with Jython
self.shape_type
= shape_type
By Richard
Hightower
def getShapeType(self):
Publisher: Addison Wesley
return
shape_type
Pub Date: June
28, 2002

Table def
of
Contents

ISBN: 0-201-61616-5

setFill(self,
value):
Pages: 640
self.fill = value
Characterized by ease of use, richness of expression, and concise syntax, Python has

def setShapeColor(self,
color):
remained a premier programming
language for more than a decade, and is used by
self.color
=
color
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise

class DrawShapes(JFrame):
application development.

def __init__(self):
This tutorial begins with coverage of some of the basics of Python programming. Using
JFrame.__init__(self,
title='Draw
Shapes',
visible=1,
plenty
of skill-building exercises and interactive
programming
sessions, this
book will
help thosesize=(400,400))
new to programming develop an understanding of concepts and practical
self.__init__toolbar()
techniques.
For experienced programmers, the book demonstrates Python's breadth of
self.__init__options()
capabilities
and shows the ways that Python interfaces with Java APIs for professional
application development.

self.statusPane = StatusBox()
Python
Programming with the Java(TM) Class Libraries: A Tutorial
for Building Web
self.contentPane.add(self.statusPane,
BorderLayout.SOUTH)
and Enterprise Applications with Jython covers important topics such as:

self.PaintPane = PaintBox(self.statusPane)
self.contentPane.add(self.PaintPane, BorderLayout.CENTER)
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
self.pack()

defPython
close(event):
basics, including operators, string formatting, namespaces, classes, errors,
mainWindow.visible=0
and exceptions
mainWindow.dispose()
from java.lang
import System
Object-oriented
programming concepts
System.exit(0)
File input/output

global mainWindow
Python's intrinsic
mainWindow
= functions
self
self.windowClosing=close
Formatting, parsing, and manipulating strings

def __init__toolbar(self):
Interfacing with the Java APIs and working with Java Streams
toolbar = ToolBox()
Using Python and Java Swing to create GUIs

# Add the rectangle button to the toolbar


rect
=
4, 20, 20))
WorkingShapeButton(Rectangle(4,
with SQL and JDBC(TM)
toolbar.add(rect)
rect.actionPerformed
= self.rect_pressed
Python and Java applets
In addition, the
instructions
for downloading
installing the Python
# book
Add contains
the oval
button
to the and
toolbar
language
Java Development Kit (JDK).4,
Terminology,
definitions, explanations,
oval and
= the
ShapeButton(Oval(4,
10, 20))
andtoolbar.add(oval)
numerous code samples make this book a useful learning experience.

oval.actionPerformed = self.oval_pressed

Whether you are a sophisticated computer user new to programming or a serious


application
developer, Python Programming with theBorderLayout.WEST)
Java(TM) Class Libraries will
self.contentPane.add(toolbar,
give you insight into the power of Python and the know-how to put it to work.

def rect_pressed(self, event):


self.PaintPane.setShapeType(PaintBox.RECTANGLE)

777

def oval_pressed(self, event):

def

self.PaintPane.setShapeType(PaintBox.OVAL)
Python
Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
fill_clicked(self,
event):
By Richard Hightower
if(event.stateChange==ItemEvent.SELECTED):
Publisher:self.PaintPane.setFill(1)
Addison Wesley
Pub Date: June 28, 2002

Table of
Contents

elif
(event.stateChange==ItemEvent.DESELECTED):
ISBN:
0-201-61616-5
self.PaintPane.setFill(0)
Pages: 640

def color_changed(self,event):
Characterized by ease of use, richness of expression, and concise syntax, Python has
colorname
event.item
remained
a premier=programming
language for more than a decade, and is used by
color
=
self.colors_dict[colorname]
novices and professionals alike. In particular, its close relationship to Java(TM) makes
theself.PaintPane.setShapeColor(color)
two languages, when used in combination, ideal for Web and distributed enterprise
application development.

def __init__options(self):
optionsPane
= coverage
JPanel()
This
tutorial begins with
of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
# to
Set
up the develop
checkbox
item for
the fill
option
help those new
programming
an understanding
of concepts
and practical
check For
= JCheckBox('Fill')
techniques.
experienced programmers, the book demonstrates Python's breadth of
optionsPane.add(check)
capabilities
and shows the ways that Python interfaces with Java APIs for professional
check.itemStateChanged
= self.fill_clicked
application development.
Python Programming
Java(TM)
Class
Libraries:
A Tutorial for Building Web
# Set with
up the
the
choice
for
color
andcolors
Enterprise=Applications
with Jython covers important topics such as:
JComboBox()

self.colors_dict = {'blue':Color.blue,
'green':Color.green,
Fundamental programming
concepts, including statements, expressions,
'red':Color.red,
interpreters, and compilers
'yellow':Color.yellow,
'orange':Color.orange,
Python basics, including operators, string formatting, namespaces, classes, errors,
'cyan':Color.cyan,
and exceptions
'pink':Color.pink,
'gray':Color.gray
Object-oriented programming
concepts
}
forFilecolor
in self.colors_dict.keys():
input/output
colors.addItem(color)
Python's intrinsic functions

colors.setSelectedItem('red')
Formatting, parsing, and manipulating strings

optionsPane.add(colors)
Interfacing with the Java APIs and working with Java Streams
colors.itemStateChanged = self.color_changed
Using Python and Java Swing to create GUIs

self.contentPane.add(optionsPane, BorderLayout.NORTH)
Working with SQL and JDBC(TM)

if __name__ == '__main__':
frame = DrawShapes()
Python and Java applets
In functionality
addition, the we
book
contains
instructions
downloading and installing the Python
Notice that, for all the
get,
the code
is relative for
simple.
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
Now let's fire up DrawShapes
and draw
some rectangles
and
ovals.
Figurelearning
15-3 is experience.
a screen dump of what we're
and numerous
code samples
make this
book
a useful
going to do.
Whether you are a sophisticated computer user new to programming or a serious
application
developer,
Python
Programming
with the Java(TM)
Class Libraries will
Figure 15-3.
Screen
Dump
of the DrawShapes
Example
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower
Publisher: Addison Wesley
Pub Date: June 28, 2002

ISBN: 0-201-61616-5

Table of
Contents

Pages: 640

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
Object-oriented programming concepts
File input/output

Phase 2: DrawShapesAdding Text


Python's intrinsic functions
We've seen how DrawShapes handles mouse events. Now let's extend it to include a text shape that handles
Formatting,
manipulating
strings
keyboard events. In addition
to text, thisparsing,
secondand
phase
of our example
will add squares, rounded rectangles, and
circles to show the design flaw of phase 1, which we'll have to wait until phase 3 to correct.
Interfacing with the Java APIs and working with Java Streams
To add a text shape, we need to do the following:
Using Python and Java Swing to create GUIs
Working
withmodule.
SQL and JDBC(TM)
Define a text shape in
the Shapes
Python
and Java
Add a shape button to
the toolbar
thatapplets
represents text.
In the
addition,
the book
instructions
for downloading
and installing the Python
Add support for
text mode
to thecontains
mousePress
event
handler.
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
Set up event handling
in the paint
box for the
following
user
actions:
and numerous
code samples
make
this book
a useful
learning experience.
Whether you are a sophisticated computer user new to programming or a serious

1. Clickingapplication
a point in the
paint box
to make
it the starting
position
of the text
developer,
Python
Programming
with
the Java(TM)
Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

2. Entering text

777

3. Pressing the Backspace key to delete the last character entered


4. Pressing Enter to end the text entry

3.
4.
Python Programming with the Java Class Libraries: A Tutorial for Building
The result
is that the bounding rectangle of the text is calculated and the area is repainted
Web and Enterprise Applications with Jython
immediately by force.
By Richard Hightower

The Text Class

Publisher: Addison Wesley


Pub Date: June 28, 2002

The Text class extends the Shape class and is defined in the Shapes module. It has font, string, and color
ISBN: 0-201-61616-5
attributes,
are passed via Shape's constructor. Text must be passed a reference to the component where
Tablewhich
of

Pages: 640
it willContents
be drawn so that it can acquire the font metrics, which it uses to calculate its ascent, descent, width, and
height. (Look up java.awt.FontMetrics in the Java API documentation to learn more about fonts.)
Characterized by ease of use, richness of expression, and concise syntax, Python has
Ascent and descent determine how far above and below the baseline a character extends (more on this later).
remained a premier programming language for more than a decade, and is used by
novices
and professionals
alike. In particular, its close relationship to Java(TM) makes
Here's the Text class
constructor
(from TwoShapes.py).
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
Class Text(Shape):

def __init__(self, x, y, string, font, component, color=None):


This
tutorial begins with coverage ofx,
some
the basics of Python programming. Using
Shape.__init__(self,
y,of color=color)
plenty
of
skill-building
exercises
and
interactive
programming sessions, this book will
fm = component.getFontMetrics(font)
help
those
new
to
programming
develop
an
understanding
self.width = fm.stringWidth(string) of concepts and practical
techniques.
For experienced
programmers, the+book
demonstrates Python's breadth of
self.height
= fm.maxAscent
fm.maxDescent
capabilities
and
shows
the
ways
that
Python
interfaces
with Java APIs for professional
self.ascent = fm.maxAscent
application
development.
self.descent
= fm.maxDescent
self.font = font
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
self.string = string
and Enterprise Applications with Jython covers important topics such as:

Text overrides both the draw_outline() and draw_filled() methods. Draw_filled() calls
draw_outline() because
Text doesn't
differentiate
between
filled and
unfilledexpressions,
mode.
Fundamental
programming
concepts,
including
statements,
draw_outline() changes
the
font
to
Text
's
font,
saving
the
original
to
be
restored
after the call to
interpreters, and compilers
drawString(), which does the actual drawing. Saving and restoring the graphics context attributes ensure
thatdraw_outline()Python
doesn'tbasics,
adversely
affect other
graphics
operations.
including
operators,
string
formatting, namespaces, classes, errors,
and exceptions
Here's the code for draw_outline() (Two\Shapes.py):
Object-oriented programming concepts

def draw_outline(self, graphics):


File input/output

if(self.font):
#Get
thefunctions
original font.
Python's
intrinsic
font = graphics.font
Formatting,
and manipulating
#Set parsing,
the graphics
to strings
this font.
graphics.font = self.font

Interfacing with the Java APIs and working with Java Streams

#Draw the string.


Using Python and Java Swing to create GUIs
graphics.drawString(self.string, self.x, self.y)
if(self.font):
Working with SQL and JDBC(TM)
# Set the graphics back
# and
to Java
theapplets
original font.
Python
graphics.font = font
In addition, the book contains instructions for downloading and installing the Python
language and thegraphics):
Java Development Kit (JDK). Terminology, definitions, explanations,
def draw_filled(self,
and numerous code samples make this book a useful learning experience.
self.draw_outline(graphics)
you are a ,sophisticated
user
new to
or calculate
a serious the area
Text's final methodWhether
is getRect()
which, you'llcomputer
remember,
is used
byprogramming
PaintBox to
application
developer,
the Java(TM)
Librarieshowever,
will
that needs to be redrawn.
Most of
the otherPython
shapes Programming
simply use the with
inherited
version ofClass
this method;
give youtheinsight
into the
powerfor
of Python
andbecause,
the know-how
to put
it to
work.
Text needs it to calculate
bounding
rectangle
the string
unlike the
other
shape
classes, its x,y
coordinates don't begin in the upper left corner, as shown in Figure 15-4.

777

Figure 15-4. Baseline, Starting Point, Width, Ascent, and Descent

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower
Publisher: Addison Wesley
Pub Date: June 28, 2002

ISBN: 0-201-61616-5

Table of
Contents

Pages: 640

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
GetRect() calculates the rectangle by moving its starting point to the upper left corner. The x,y axis
increases down and Python
to the right,
so subtracting
moves
theLibraries:
point up (ifA down
is positive,
up isWeb
negative).
Programming
with the
the ascent
Java(TM)
Class
Tutorial
for Building
and Enterprise Applications with Jython covers important topics such as:

def getRect(self):
return self.x, self.y-self.ascent, self.width, self.height
Fundamental programming concepts, including statements, expressions,
The Text Class Code interpreters, and compilers
basics,seen
including
formatting,
namespaces,
Text is the most complexPython
shape we've
so far,operators,
and it isn'tstring
as complex
as it seems.
Here itclasses,
is in itserrors,
entirety
(fromTwo\Shapes.py):

and exceptions

Object-oriented programming concepts


class Text(Shape):
def __init__(self, x, y, string, font, component, color=None):
File input/output
Shape.__init__(self,
x, y, color=color)
fm =Python's
component.getFontMetrics(font)
intrinsic functions
self.width = fm.stringWidth(string)
self.height
= fm.maxAscent
+ fm.maxDescent
Formatting, parsing,
and manipulating strings
self.ascent = fm.maxAscent
self.descent
Interfacing with =thefm.maxDescent
Java APIs and working with Java Streams
self.font = font
Using Python and
Java Swing to create GUIs
self.string
= string
Working with SQL andgraphics):
JDBC(TM)
def draw_outline(self,
Python and Java applets

if(self.font):
#Get instructions
the original
font.and installing the Python
In addition, the book contains
for downloading
font
=
graphics.font
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
#Setmake
thethisgraphics
this
font.
and numerous code samples
book a usefulto
learning
experience.
graphics.font = self.font
Whether you are a sophisticated computer user new to programming or a serious
#Draw the
application developer,
Pythonstring.
Programming with the Java(TM) Class Libraries will
graphics.drawString(self.string,
self.x,
give you insight into the power of Python and the know-how
to put itself.y)
to work.

if(self.font):
#Set the graphics back to the original font.
graphics.font = font

777

Python Programming with


the Java Class Libraries: A Tutorial for Building
def draw_filled(self,
graphics):
Web
and
Enterprise
Applications
with Jython
self.draw_outline(graphics)
By Richard Hightower

def getRect(self):
Publisher:self.x,
Addison Wesley
return
self.y-self.ascent, self.width, self.height
Pub Date: June 28, 2002
ISBN: 0-201-61616-5
Supporting
the Text Class
Table of

Contents

Pages: 640

Now let's add support for Text to our DrawShapes modulefont name and point size options and
Characterized
easetypical
of use,user
richness
expression,
syntax,we
Python
keyboard event handling.
Here are by
some
actionsofthat
illustrateand
the concise
type of things
need:has
remained a premier programming language for more than a decade, and is used by
novices
and button
professionals
alike. In particular,
its close relationship to Java(TM) makes
1. Clicking the Text
shape
in the DrawShapes
toolbar
the
two
languages,
when
used
in
combination,
ideal for Web and distributed enterprise
2. Changing the font name in the options pane
application
development.
3. Clicking on the PaintBox panel
4. Typing characters
This key
tutorial begins with coverage of some of the basics of Python programming. Using
5. Pressing the Enter
plenty of skill-building exercises and interactive programming sessions, this book will
thosefor
new
programming
develop
understanding
and practical
Step 1 fires the eventhelp
handler
thetoShape
button, which
setsanthe
shape type ofoftheconcepts
PaintBox
panel to
techniques.
For
experienced
programmers,
the
book
demonstrates
Python's
breadth
of the
TEXT. Step 2 fires the event handler for font choice, which sets PaintBox 's font attribute. Step 3 fires
capabilities
and
shows
the
ways
that
Python
interfaces
with
Java
APIs
for
professional
mousePressed event, whose handler sets the x,y position of the text. Then Step 4 fires the keyTyped
event, whose handlerapplication
draws textdevelopment.
on the paint box. Step 5 causes a Text class to be instantiated and added to
PaintBox 'sshapes attribute.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise
Applications
covers
important topics
such as: (I got tired of
PaintBox also handles
the Backspace
key for with
thoseJython
of us who
occasionally
make mistakes.
typing "Hekko World.")

Fundamental
concepts,
statements,
expressions, frame. We
To implement Text we first
need to addprogramming
the text shape
button toincluding
the toolbar
of the DrawShapes
compilers
create an instance of Textinterpreters,
and pass it and
to the
ShapeButton class.
Python basics, including operators, string formatting, namespaces, classes, errors,
def __init__toolbar(self):
and exceptions
toolbar
= ToolBox()
#Add the rectangle button to the toolbar
programming concepts
rectObject-oriented
= ShapeButton(Rectangle(4,
4, 20, 20))
toolbar.add(rect)
File input/output
rect.actionPerformed = self.rect_pressed
...
Python's intrinsic functions
...
Formatting, parsing, and manipulating strings

# Set the current font to Arial,


Interfacing
with the
Javathe
APIs FontMetrics
and working with Java Streams
# then
get

font = Font("Arial", Font.PLAIN, 20)


Python and Java Swing to create GUIs
fm =Using
self.getFontMetrics(font)
Working with SQL and JDBC(TM)

#Add the Text button to the toolbar.


text=ShapeButton(Text(2,
2+fm.maxAscent, "A", font, self))
Python and Java applets
toolbar.add(text)
= self.text_pressed
Intext.actionPerformed
addition, the book contains instructions
for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
As you can see, we need
to get the code
font metrics
put the
shape
in thelearning
button. experience.
The font metrics calculate
and numerous
samplestomake
thistext
book
a useful
where to move the start position of the text so that it's displayed in the button's upper right corner. Then we have
to set the event handler
for theyou
button's
event tocomputer
text_pressed
Whether
are a action
sophisticated
user new to. programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
def text_pressed(self,
event):
give you insight into
the power of Python and the know-how to put it to work.

self.PaintPane.setShapeType(PaintBox.TEXT)
self.PaintPane.requestFocus()

777

Thetext_pressed event handler sets the shape type of the paint box to TEXT. Calling requestFocus
gives the paint box input focus, which is essential for it to receive key events. There can be no key events

without input focus. Python Programming

with the Java Class Libraries: A Tutorial for Building


Web and Enterprise Applications with Jython
the DrawShapes
frame
needs the font options (point size and typeface) added to its options pane.
By Richard
Hightower

Next,
Here's the code:

Publisher: Addison Wesley

def __init__options(self):
Pub Date: June 28, 2002
optionsPane
= Panel()
ISBN: 0-201-61616-5
optionsPane.add(Label("Font"))
Table of

Contents

Pages: 640

#Set up the Font point List.


Characterized
by ease of use, richness of expression, and concise syntax, Python has
point_list
= Choice()
remained
a
premier
programming language for more than a decade, and is used by
points = (8,9,10,12,14,16,18,20,24,32)

novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two in
languages,
when used in combination, ideal for Web and distributed enterprise
for point
points:
application
development.
point_list.add(str(point))
This tutorial begins with coverage of some of the basics of Python programming. Using

optionsPane.add(point_list)
plenty of skill-building exercises and interactive programming sessions, this book will
point_list.itemStateChanged = self.point_changed

help those new to programming develop an understanding of concepts and practical


techniques. For experienced programmers, the book demonstrates Python's breadth of
#Set up font List.
capabilities and shows the ways that Python interfaces with Java APIs for professional
from java.awt import GraphicsEnvironment
application development.

ge = GraphicsEnvironment.getLocalGraphicsEnvironment()
fonts Python
= ge.getAvailableFontFamilyNames()
Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
fonts_list
= Choice()
and Enterprise
Applications with Jython covers important topics such as:
for font in fonts:
fonts_list.add(font)
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
optionsPane.add(fonts_list)

fonts_list.itemStateChanged = self.font_changed
Python basics, including operators, string formatting, namespaces, classes, errors,
exceptions
The__init_optionsand
method
creates a list of point sizes and adds it to a choice control called
point_list. Next it gets a list of fonts from
Object-oriented programming concepts
GraphicsEnvironment.getAvailableFontFamilyNames
and adds it to a choice control
calledfont_list.font_list and point_list are added to the options pane, and event handlers
File input/output
are set up for both.
Python's intrinsic
The event handler for font_list
sets thefunctions
name property of the paint pane (an instance of PaintBox )
when the user selects a font name. event.item contains the font name selected by the user and is passed to
Formatting, parsing, and manipulating strings
thesetFontName() method of the PaintBox instance, which sets the instance's font.
Interfacing with the Java APIs and working with Java Streams
The event handler for point_list converts event.item to an integer and then sets the paint pane's
point size property.
Using Python and Java Swing to create GUIs
Here are the event handlersWorking
for both with
font_list
and point_list:
SQL and JDBC(TM)

def font_changed(self,
Python andevent):
Java applets
self.PaintPane.setFontName(event.item)
In addition, the book contains instructions for downloading and installing the Python

def point_changed(self,
event):
language and the Java
Development Kit (JDK). Terminology, definitions, explanations,
self.PaintPane.setFontPoint(int(event.item))
and numerous code samples make this book a useful learning experience.
That about does it forWhether
the changes
made
to DrawShapes
to support
I'll describe or
thea changes
you are
a sophisticated
computer
usertext.
new Now
to programming
serious made to
PaintBox to add application
text shape support.
This
is the Programming
interesting part.with the Java(TM) Class Libraries will
developer,
Python
give you insight into the power of Python and the know-how to put it to work.

Test and PaintBox

777

PaintBox adds another shape type, TEXT. It adds three attributes to its class instance in its constructor:
text (a string), which denotes the text being typed by the user but not yet entered inthat is, the transitional

text;startText (an
integer
representing awith
Boolean
value), Class
whichLibraries:
denotes whether
or notfor
a text
operation has
Python
Programming
the Java
A Tutorial
Building
begun; and text_in
, which
holds the transitional
instance
the text shape, that is, the text being keyed in
Web
and Enterprise
Applications
withofJython
and edited. When theByshape
type
is TEXT and the user clicks the paint box, startText is set to true, and
Richard
Hightower
PaintBox begins processing key events. The key event handlers control the text operation and add characters
to the text attribute. Publisher: Addison Wesley
Pub Date: June 28, 2002

Here's the definition for PaintBox and its constructor (from two\DrawShapes.py):
Table of
class
Paint
Contents

...
...

ISBN: 0-201-61616-5

Pages: 640
(Panel):

box
RECTANGLE=1
OVAL=2Characterized by ease of use, richness of expression, and concise syntax, Python has

remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
TEXT=4the two languages, when used in combination, ideal for Web and distributed enterprise
application development.

def __init__(self, status):


This tutorial begins with coverage of some of the basics of Python programming. Using
Panel.__init__(self)
plenty of skill-building exercises and interactive programming sessions, this book will
self.status = status
help those new to programming develop an understanding of concepts and practical
self.shapes = Shapes()
techniques. For experienced programmers, the book demonstrates Python's breadth of
self.shape_type = PaintBox.RECTANGLE
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.

self.mouseDragged = self.handle_mouseDragged

...
...

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

self.keyPressed = self.handle_keyPressed
self.keyTyped = self.handle_keyTyped

Fundamental programming concepts, including statements, expressions,


interpreters, and
self.point
= compilers
20

self.fontname = "Arial"
Python basics,
operators, string formatting,
namespaces, classes,
errors,
self.font
= including
Font(self.fontname,
Font.PLAIN,
self.point)
and exceptions

self.text = ""
Object-oriented programming
concepts
self.startText
= 0
self.text_in
= None
File input/output
...Python's intrinsic functions
...
Formatting, parsing, and manipulating strings
When the user presses the mouse button, the mousePress event handler is called, which sets startText
to true and sets the text to an
empty string
theJava
shape
typeand
is TEXT
. This
the text's starting point. In the
Interfacing
withifthe
APIs
working
withdefines
Java Streams
following example, code that has been added to two\DrawShapes.py is hightlighted in bold.
Using Python and Java Swing to create GUIs

def handle_mousePress(self, event):


...
...

Working with SQL and JDBC(TM)


Python and
Java applets
self.last
= self.start
= event.point
the book contains instructions
for downloading and installing the Python
ifIn addition,
(self.shape_type
== PaintBox.TEXT):
language
and
the
Java
Development
Kit
(JDK).
Terminology, definitions, explanations,
self.text = ""
and numerous
code
samples
make
this
book
a
useful
learning experience.
self.startText = 1

Whether you are a sophisticated computer user new to programming or a serious


application developer, Python Programming with the Java(TM) Class Libraries will
drawing a text shape.
give you insight into the power of Python and the know-how to put it to work.

PaintBox uses only keyPressed to handle control keys and keyTyped to handle character keys when
ThekeyPressed event handler handles the Enter and Backspace keys. When Enter is pressed, the text shape
being defined is added to the paint box's shapes collection. Here's the code:

777

def handle_keyPressed(self, event):

self.ignore
= 0
Python Programming
with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
# Perfom
actions for drawing text
By Richard
Hightower

# if this in text draw mode.


if self.shape_type
== PaintBox.TEXT and self.startText:
Publisher: Addison Wesley
Pub Date: June 28, 2002
Table of

Contents

If the user
ISBN:#0-201-61616-5

presses the Enter key,


#
We
add
this
shape to the shape list.
Pages: 640
if (event.keyCode == KeyEvent.VK_ENTER):
self.shapes.addShape(self.text_in)
Characterized
by ease of use, richness of expression, and concise syntax, Python has
self.startText
= 0 for more than a decade, and is used by
remained a premier
programming language
self.text_in
=
None its close relationship to Java(TM) makes
novices and professionals alike. In particular,

the two languages, when used in combination, ideal for Web and distributed enterprise
When the Backspace key is pressed, the last character of the text string is removed, and the ignore attribute of
application development.
PaintBox is set to true. ignore is needed because the Backspace key generates a character (here '\b') that
we don't want to show
uptutorial
in our text
shape
(itcoverage
appears as
square).
A true
value
tells theprogramming.
keyTypedUsing
event
This
begins
with
ofasome
of the
basics
of Python
handler to disregard plenty
any such
character.
Also
when
the
Backspace
key
is
pressed,
a
new
text
shape
is
created
of skill-building exercises and interactive programming sessions, this book will and
assigned to the text_in
attribute
(whose
last character
wasanjust
removed), which
forces aand
repaint
of
help those
new to
programming
develop
understanding
of concepts
practical
text_in's boundstechniques.
(before the For
backspace
operation).
experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional

def handle_keyPressed(self, event):


application development.
self.ignore = 0
# Perform
for
drawing
Python Programming
withactions
the Java(TM)
Class
Libraries: Atext
Tutorial for Building Web
#
if
this
in
text
draw
mode.
and Enterprise Applications with Jython covers important topics such as:
if self.shape_type == PaintBox.TEXT and self.startText:
...
...

Fundamental programming concepts, including statements, expressions,


interpreters, and compilers

# If the user presses the Backspace key,


Python basics, #
including
operators,the
stringlast
formatting,
namespaces,in
classes,
we delete
character
theerrors,
text.
andif
exceptions
(event.keyCode == KeyEvent.VK_BACK_SPACE):

x,y,width,height = self.text_in.getRect()

Object-orientedself.ignore
programming concepts
= 1

self.text = self.text[:-1]
self.text_in=Text(self.start.x, self.start.y, \
Python's intrinsic functionsself.text,self.font,self, self.color)
self.repaint()(x,y,width+1, height+1)
File input/output

Formatting, parsing, and manipulating strings


Unlike the keyPressed handler, the keyTyped handler works with characters the user types in, which are
collected in the text string. Interfacing
After each with
character
is typed,
newworking
text shape
created (text_in). The
the Java
APIsaand
withobject
Java is
Streams
keyTyped event handler uses the bounds of text_in to force a repaint so that the shape is redrawn.
Using Python and Java Swing to create GUIs

def handle_keyTyped(self,event):
Working with SQL and JDBC(TM)

# See if this is in text draw mode,


Python
andbackspace
Java applets was not pressed
# and
the
if self.shape_type == PaintBox.TEXT and self.startText \
In addition, the book contains instructions for downloading and installing the Python
and not self.ignore:
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
# Get the character typed, add it to the text.
and numerous code samples make this book a useful learning experience.
self.text = self.text + event.keyChar
Whether you are a sophisticated computer user new to programming or a serious
# ForcePython
theProgramming
text to with
be the
shown.
application developer,
Java(TM) Class Libraries will
#
Create
the
Text
instance,
and
force
repaint().
give you insight into the power of Python and the know-how
to put
it to work.

self.text_in = Text(self.start.x, self.start.y, \


self.text, self.font, self, self.color)
x,y,width,height = self.text_in.getRect()
self.repaint()(x,y,width+1, height+1)

777

Thepaint()method
checks
to see if the text_in
shape exists.
so, it draws
it. Remember,
the
Python
Programming
with the Java
Class If
Libraries:
A Tutorial
for Building
text_in attributeWeb
corresponds
to the current
shape, thatwith
is, the
one being worked on.
and Enterprise
Applications
Jython
By Richard Hightower

def paint(self, graphics):


Publisher: Addison Wesley

#Draw
all of the shapes.
Pub Date: June 28, 2002
self.shapes.paint(graphics)

Table of
Contents

ISBN: 0-201-61616-5

Pages: 640

#For showing text while we type


if(self.text_in):
Characterized by ease of use, richness of expression, and concise syntax, Python has
self.text_in.paint(graphics)

remained a premier programming language for more than a decade, and is used by
novices
and professionals
alike. In
close relationship
PaintBox also creates
several
methods to change
itsparticular,
font anditspoint
attributes. to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
def setFontName(self,
font):

self.fontname = font
This tutorial
begins with coverage of some of
the basics of Python
programming. Using
self.font
= Font(self.fontname,
Font.PLAIN,
self.point)

plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
def setFontPoint(self,point):
techniques.
experienced programmers, the book demonstrates Python's breadth of
self.point
= For
point
capabilities
and
shows the ways that Python Font.PLAIN,
interfaces with Javapoint)
APIs for professional
self.font = Font(self.fontname,
application development.
So now we've added text shape support. Oh, yes, I said earlier that we would add squares, circles, and rounded
Programming
with these
the Java(TM)
Class
Tutorial
Building
Web
rectangles. Well, wePython
won't go
into detail about
shapes, but
we Libraries:
will take aAlook
at thefor
problem
they
cause.
and Enterprise Applications with Jython covers important topics such as:
If all you wanted out of this chapter was an introduction to graphics programming, you just got it. But if you
want to learn what makes dynamic object-oriented programming tick, read on. We're going to modify
Fundamental programming concepts, including statements, expressions,
DrawShapes and its classes and make them significantly smaller and more extensible. In other words, we're
interpreters, and compilers
going to write tight, dynamic, object-oriented Python code.
Python basics, including operators, string formatting, namespaces, classes, errors,
DrawShapes' Ugly, Inefficient,
Nonextensible Code
and exceptions
Let's see what's wrong withObject-oriented
DrawShapes asprogramming
it stands now.concepts
We'll start with the DrawShapes class. First look
at__init__toolbar (from two\DrawShapes.py).
File input/output

def __init__toolbar(self):
Python's=intrinsic
functions
toolbar
ToolBox()
Formatting,
and manipulating
strings to the toolbar
#Add parsing,
the Rectangle
button

rectInterfacing
= ShapeButton(Rectangle(4,
4, 20, 10))
with the Java APIs and working with Java Streams
toolbar.add(rect)
rect.actionPerformed
Using Python and Java Swing=toself.rect_pressed
create GUIs
#Add
button to the toolbar
Working
withthe
SQLCircle
and JDBC(TM)
circle = ShapeButton(Circle(4, 4, 10))
Python and Java applets
toolbar.add(circle)
circle.actionPerformed = self.circle_pressed
In addition, the book contains instructions for downloading and installing the Python
language and
the Java
Development
Kit (JDK).
definitions, explanations,
#Add
the
Oval button
toTerminology,
the toolbar
and
numerous
code
samples
make
this
book
a
useful
learning
experience.
oval = ShapeButton(Oval(4, 4, 10, 20))

toolbar.add(oval)

Whether you are a sophisticated computer user new to programming or a serious


oval.actionPerformed = self.oval_pressed
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

#Add the Square button to the toolbar


square = ShapeButton(Square(4, 4, 20))
toolbar.add(square)
square.actionPerformed = self.square_pressed

777

#Add the with


RoundRectangle
buttonA Tutorial
to thefortoolbar
Python Programming
the Java Class Libraries:
Building
rrect
= ShapeButton(RoundedRectangle(4,
4, 20, 20))
Web
and Enterprise
Applications with Jython
toolbar.add(rrect)
By
Richard Hightower
rrect.actionPerformed = self.round_rect_pressed
Publisher: Addison Wesley

# June
Set28,
the
Pub Date:
2002current

Table of
Contents

font to Arial,
#
then
get
the
FontMetrics
ISBN: 0-201-61616-5
fontPages:
= Font("Arial",
Font.PLAIN, 20)
640
fm = self.getFontMetrics(font)
Characterized by ease of use, richness of expression, and concise syntax, Python has
Add programming
the Text language
button
remained a#premier
for to
morethe
than atoolbar.
decade, and is used by
text=ShapeButton(Text(2,
2+fm.maxAscent,
font,
novices and professionals alike. In particular, its close relationship to"A",
Java(TM)
makes self))
the two languages, when used in combination, ideal for Web and distributed enterprise
toolbar.add(text)
application
development.

text.actionPerformed = self.text_pressed

This tutorial begins with coverage of some of the basics of Python programming. Using
self.add(toolbar,
BorderLayout.WEST)
plenty
of skill-building exercises
and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
Every time we definetechniques.
a new shape,
have to write
three to fivethe
lines
of demonstrates
code in __init__toolbar
Forwe
experienced
programmers,
book
Python's breadth of ; then
we have to write an event
handler
forshows
each one.
As you
see, with
just sixwith
shapes
gets pretty
messy.
capabilities
and
the ways
thatcan
Python
interfaces
JavaitAPIs
for professional
application development.

def circle_pressed(self, event):


self.PaintPane.setShapeType(PaintBox.CIRCLE)
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

def rect_pressed(self, event):


self.PaintPane.setShapeType(PaintBox.RECTANGLE)

Fundamental programming concepts, including statements, expressions,


interpreters, and compilers
def round_rect_pressed(self,
event):

self.PaintPane.setShapeType(PaintBox.ROUND_RECTANGLE)
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptionsevent):
def square_pressed(self,

self.PaintPane.setShapeType(PaintBox.SQUARE)
Object-oriented programming concepts

def oval_pressed(self,
event):
File input/output
self.PaintPane.setShapeType(PaintBox.OVAL)
Python's intrinsic functions

def text_pressed(self, event):


self.PaintPane.setShapeType(PaintBox.TEXT)
Formatting, parsing, and manipulating strings
self.PaintPane.requestFocus()
Interfacing with the Java APIs and working with Java Streams
They all look pretty similar, don't they? Why not replace all of the code above with this:
Using Python and Java Swing to create GUIs

class ShapeTool:
Working with SQL
and JDBC(TM) toolbar, PaintBox):
def __init__(self,
shape_class,
Python and
Java applets
# Use
eval to create a shape. shape_class

# holds a string representing the class.

In addition, the book contains instructions for downloading and installing the Python
self.__shape = eval(shape_class+'()')
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
button = ShapeButton(self.__shape)
and numerous code samples make this book a useful learning experience.

toolbar.add(button)
button.actionPerformed
= user
self.actionPerformed
Whether
you are a sophisticated computer
new to programming or a serious
self.PaintBox
=
PaintBox
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

def actionPerformed(self, event):


self.PaintBox.requestFocus()
self.PaintBox.setShapeType(self.__shape.__class__)
def getShape(self):return self.__shape

777

Python Programming
The ShapeTool Class

with the Java Class Libraries: A Tutorial for Building


Web and Enterprise Applications with Jython
By Richard
Hightower
__init__toolbar
uses ShapeTool
to create shape buttons, add them to the toolbar, and register

them
with an event handler. Notice that it uses strings to denote each shape's class. The ShapeTool constructor
Publisher:
uses the strings as arguments
to theAddison
built-inWesley
eval() function.
Pub Date: June 28, 2002

class DrawShapes(Frame):
ISBN: 0-201-61616-5
... Table of
Pages: 640
Contents
...
Characterized by ease of use, richness of expression, and concise syntax, Python has

def __init__toolbar(self):
remained a premier programming language for more than a decade, and is used by
toolbar
= ToolBox()
novices
and professionals
alike. In particular, its close relationship to Java(TM) makes
Shapes
= ['Square',
'Rectangle',
the
two languages,
when used in combination,
ideal for'RoundedRectangle',
Web and distributed enterprise
'Oval', 'Text', 'Circle' ]
application development.

This
begins
coverage of some of the basics of Python programming. Using
fortutorial
shape
inwith
Shapes:
plenty of skill-building
exercises and interactive programming sessions, thisself.PaintPane)
book will
shape_tool=ShapeTool(shape,toolbar,
help those new to programming develop an understanding of concepts and practical
techniques. For if
experienced
programmers, the book demonstrates Python's breadth
of
(isinstance(shape_tool.getShape(),
Text)):
capabilities and shows the ways
that
Python
interfaces
with
Java
APIs
for
professional
shape_tool.getShape().initForToolbar('A', self.P
application development.

self.add(toolbar, BorderLayout.WEST)
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise
Jython
covers
important
such as:It eliminates thirty
TheShapeTool class
defines the Applications
event handlerwith
for each
button
and
adds it totopics
the toolbar.
lines of code and five function definitions. What's more, it's extensible: Any additional shapes are just added to
the shapes list in __init__toolbar with no extra code. With the old way, for thirty shapes we'd need
Fundamental programming concepts, including statements, expressions,
thirty event handlers and about seventy-five additional lines of code. With the new way, all we need is thirty
interpreters, and compilers
entries in the shapes list.
Python basics, including operators, string formatting, namespaces, classes, errors,
Less code to write equates to less code to test and fewer bugs. In addition, we can create a text file our program
and exceptions
can read that lists the shapes we want to display. This is extremely flexible.
Object-oriented
programming
concepts
Notice that the event handler
for ShapeTool
passes the
class, not an integer representing the type. The old
way passed an integer with the type as defined by constant values in the PaintBox class. This is directly from
File input/output
the Department of Redundancy Department (with thanks to Monty Python). A class is a type, and shapes can be
uniquely identified by theirPython's
class. Now
PaintBox
intrinsic
functionsuses the class as the shape type.
Formatting, parsing, and manipulating strings
Making PaintBox Modular
Interfacing
with the. First
Java of
APIs
withevery
Java time
Streams
There's a lot wrong with the
old PaintBox
all,and
as Iworking
mentioned,
we add a shape, we need to
add a shape constant. This tightly couples shapes to PaintBox .
Using Python and Java Swing to create GUIs

class PaintBox (JComponent):


Working with SQL and JDBC(TM)
RECTANGLE=1
OVAL=2
Python and Java applets
CIRCLE=3
TEXT=4In addition, the book contains instructions for downloading and installing the Python
ROUND_RECTANGLE=5
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
SQUAREand=numerous
6
code samples make this book a useful learning experience.
...
... Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
The shape type integer
is you
passed
to PaintBox
, making
it necessary
add another
suite
to work.
PaintBox 'sif
give
insight
into the power
of Python
and the to
know-how
to put
it to
statementdrawShape()for each new shape.

777

def setShapeType(self, shape_type):


self.status.setShapeType(shape_type)

self.shape_type
= shape_type
Python Programming
with the Java Class Libraries: A Tutorial for Building
def __drawShape(self,
g, x,
y, width,
Web and Enterprise
Applications
with height):
Jython
By Richard Hightower

if self.shape_type == PaintBox.RECTANGLE:
g.drawRect(self.start.x,
self.start.y, width, height)
Publisher: Addison Wesley
Pub Date: June 28, 2002

if self.shape_type
== PaintBox.ROUND_RECTANGLE:
ISBN: 0-201-61616-5
Table of
g.drawRoundRect(self.start.x,
self.start.y, width, height, 10,10)
Pages: 640
Contents

if self.shape_type
PaintBox.OVAL:
Characterized by ease==
of use,
richness of expression, and concise syntax, Python has
g.drawOval(self.start.x,
self.start.y,
width,
height)
remained a premier programming language
for more than a decade,
and is used
by
novices and professionals alike. In particular, its close relationship to Java(TM) makes

if self.shape_type
== used
PaintBox.CIRCLE:
the two languages, when
in combination, ideal for Web and distributed enterprise
g.drawOval(self.start.x,
self.start.y, width, width)
application development.
if self.shape_type
== coverage
PaintBox.SQUARE:
This tutorial begins with
of some of the basics of Python programming. Using
g.drawRect(self.start.x,
self.start.y,
width,thiswidth)
plenty of skill-building exercises and interactive
programming sessions,
book will
help those new to programming develop an understanding of concepts and practical
There are a couple oftechniques.
things wrong
this. First,
the code for the
drawing
shape shouldPython's
be in a shape
object,
Forwith
experienced
programmers,
book ademonstrates
breadth
of not
inPaintBox . Thiscapabilities
means thatand
the shows
originalthe
code
forthat
drawShape()
isn't
modular,
and for
that's
bad. If there's a
ways
Python interfaces
with
Java APIs
professional
problem drawing a shape,
the developer
who inherits this code won't know if she should look in the Shapes
application
development.
module or in the PaintBox class.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
Code should be modular;
that is, a class
should dowith
oneJython
set of covers
related important
things. The
shapesuch
should
and Enterprise
Applications
topics
as: know how to do
shape things like draw itself, and this knowledge should be hidden from PaintBox in other words,
encapsulated.
Fundamental programming concepts, including statements, expressions,
Here's our modular versioninterpreters,
(Three\PaintBox.py):
and compilers

def createShape(self):
Python basics, including operators, string formatting, namespaces, classes, errors,
"""Create aandnew
shape with the shape_type.
exceptions
The shape_type is a Shape class."""
Object-oriented programming concepts

self.shape = self.shape_type()
File input/output
if (isinstance(self.shape,
Text)):
self.shape.setComponent(self)
Python's intrinsic functions

def setShapeType(self,
shape_type):
Formatting, parsing, and manipulating strings
"""Set the current Shape type,
then createInterfacing
an instance
ofAPIs
the
with the Java
andshape"""
working with Java Streams
self.status.setShapeType(shape_type)
self.shape_type
= shape_type
Using Python
and Java Swing to create GUIs
self.createShape()
Working with SQL and JDBC(TM)

def __drawShape(self, g, x, y, width, height):


Python and Java applets
self.shape.fromBounds(self.start.x,
self.start.y, width, height)
self.shape.draw_outline()(g)
In addition, the book contains instructions for downloading and installing the Python
language,and
the Java Development
Terminology, method,
definitions,
explanations,
In the new drawShape()
we initialize
the shape withKit
the(JDK).
fromBounds()
which
tells the shape
and
numerous
code
samples
make
this
book
a
useful
learning
experience.
to initialize itself from the given bounding rectangle. If you look at the shape classes in the code above, you'll
notice all of them either inherit the default, fromBound(), from the Shape class or implement their own
Whether you are a sophisticated computer user new to programming or a serious
version.
application developer, Python Programming with the Java(TM) Class Libraries will
theif power
the know-how
to put and
it toso
work.
The great thing aboutgive
ouryou
newinsight
code isinto
that,
we addofaPython
triangle,and
a hexagon,
an octagon,
forth, it doesn't
change. With the old __DrawShapes, each time we add a new shape we have to add another elif suite to
theif statement. Thirty shapes equal thirty elif branches.

777

This is the magic of polymorphism. All we do is tell the shape to initialize itself from the bounds we give it; we

don't care if it's a triangle


or aProgramming
parallelogram. with the Java
Python

Class Libraries: A Tutorial for Building


Web and Enterprise Applications with Jython
that thereBywas
another
place where we had a long if statement with lots of elif
Richard
Hightower

Remember
suiteshandle_mouseRelease, which created a shape based on the shape type defined by the integer
constants. The new handle_mouseRelease
does not need to do that, so it's not coupled to adding new
Publisher: Addison Wesley
shapes. Look at the differences with the few shapes we defined, and imagine what the old mouseRelease
Pub Date: June 28, 2002
handler (from Two\DrawShapes.py) would look like if we had thirty shapes.

def

ISBN: 0-201-61616-5
Table of
Pages:
640
handle_mouseRelease(self,
event):
Contents

Characterized
ease of use,
of expression, and concise syntax, Python has
# byPrint
therichness
status
remained
a
premier
programming
language
for more than a decade,
and is used by
self.status.setMouseRelease(event.x,
event.y)
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages,
when used inthe
combination,
Web and
distributed enterprise
# Calculate
widthideal
andforthe
height
application
development.
width = abs(self.start.x - event.x)

height = abs(self.start.y - event.y)

This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
shape = None #hold the shape we are about to create
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
# Create shape based on the current shape type.
capabilities and shows the ways that Python interfaces with Java APIs for professional
# Then add the shape to self.shapes.
application development.

if self.shape_type == PaintBox.RECTANGLE:
shape with
= Rectangle(self.start.x,
self.start.y,
Python Programming
the Java(TM) Class Libraries: A Tutorial
for Building Web width,
height,
self.color,
self.fill)
and Enterprise Applications with Jython covers important topics such as:
elif self.shape_type == PaintBox.OVAL:
Fundamental
concepts, including statements,
expressions, width, height,
shapeprogramming
= Oval(self.start.x,
self.start.y,
interpreters, and compilers
self.color, self.fill)
basics, including operators,
string formatting, namespaces, classes, errors,
elifPython
self.shape_type
== PaintBox.CIRCLE:
and exceptions
shape = Circle(self.start.x, self.start.y, width/2,
self.color, self.fill)
Object-oriented programming concepts

elifFileself.shape_type
== PaintBox.SQUARE:
input/output
shape = Square(self.start.x, self.start.y, width,
self.color, self.fill)
Python's intrinsic functions
elifFormatting,
self.shape_type
== PaintBox.ROUND_RECTANGLE:
parsing, and manipulating
strings
shape = RoundedRectangle(self.start.x, self.start.y,
Interfacing with the Java
APIs and
working with
Java Streams self.fill)
width,
height,
self.color,
Using shape
Python and
Swing to create GUIs
if not
isJava
None:
self.shapes.addShape(shape)
Working with SQL and JDBC(TM)
x,y,width,height = shape.getRect()
height+1)
Pythonself.repaint(x,y,width+1,
and Java applets
Here's the new mouseRelease
(Three\DrawShapes.py):
In addition, the handler
book contains
instructions for downloading and installing the Python

language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.

def handle_mouseRelease(self, event):

the status
Whether you#arePrint
a sophisticated
computer user new to programming or a serious
self.status.setMouseRelease(event.x,
event.y)
application developer, Python Programming with the Java(TM)
Class Libraries will
give you insight into the power of Python and the know-how to put it to work.
# Calculate the width and the height
width = abs(self.start.x - event.x)
height = abs(self.start.y - event.y)

777

# Set the
bounds,
i.e.,A Tutorial for Building
Python Programming
withshape
the Java
Class Libraries:
# the Applications
bounds the
shape
Web and Enterprise
with
Jython initializes from.
# Add the shape to the shape list.
By Richard Hightower
# Calculate the shape actual bounds,
and Wesley
repaint().
Publisher:#Addison

self.shape.fromBounds(self.start.x,
self.start.y, width, height,
Pub Date: June 28, 2002
self.color, self.fill)
ISBN: 0-201-61616-5
Table of
self.shapes.addShape(self.shape)

Pages: 640
Contents
x,y,width,height = self.shape.getRect()
self.repaint(x,y,width+1,
height+1)
Characterized
by ease of use, richness of expression,
and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
# Create alike.
a new
shape.its close relationship to Java(TM) makes
novices and professionals
In particular,
self.createShape()
the
two languages, when used in combination, ideal for Web and distributed enterprise
application development.
I don't want you to confuse the fooling around with objects we're doing with defining an extensible architecture
for an application. I just
to highlight
those
simple of
changes
andtheshow
thatofdynamic
object-orientedUsing
Thiswant
tutorial
begins with
coverage
some of
basics
Python programming.
programming saves us
huge
headaches.
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
A Broken Record
application development.
Remember toPython
read Object-Oriented
Analysis
and Design
withLibraries:
Applications
(Booch,for
1994)
and then
Programming with
the Java(TM)
Class
A Tutorial
Building
Web
Design Patterns
et al.,
1995). with Jython covers important topics such as:
and(Gamma
Enterprise
Applications
Try these exercises, which extend the drawing package in directory 3:
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
Add three new shapes: a triangle (use drawPolygon and fillPolygon), a line, and a scribble.
Python basics, including operators, string formatting, namespaces, classes, errors,
andon
exceptions
Create an Undo button
the options pane that allows users to undo the last shape drawn.

Object-oriented
programming
Create a button on
the options pane
that allows concepts
a user to change the z-order of the shapes (that is, the
order in which the shapes are "stacked" in the view); this might pop up a dialog box that has a list of
input/output
shapes representing File
the z-order.
Python's
intrinsic
functions
Add the ability to drag
an already
drawn
shape to a new position. You'll need to do hit testing for the
shape.
Formatting, parsing, and manipulating strings
Add the ability to select a shape and change its color.
Interfacing with the Java APIs and working with Java Streams
Create a composite shape, and call it TextBox. It should contain two shapes: the text to be drawn and
Using Python and Java Swing to create GUIs
the bounding rectangle. The user draws the textbox first and adds text to it. The text entered word-wraps;
that is, it stays withinWorking
the bounds
the rectangle,
filling the box left to right and then top to bottom, and if
withofSQL
and JDBC(TM)
the text is too long for one line, it starts a new one. If there are too many lines for the bounds, only the text
that fits is shown. Python and Java applets
If you don't do at least
first exercise,
won't get
much outfor
of downloading
this chapter. If
youinstalling
can handle
last one,
In the
addition,
the bookyou
contains
instructions
and
the the
Python
you're well on your way
to programmer
stardom.
language
and the Java
Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.

Summary

Whether you are a sophisticated computer user new to programming or a serious


application developer, Python Programming with the Java(TM) Class Libraries will
This chapter mainly give
covered
using
Java AWT.
Weknow-how
learned about
theitdifferent
youevents
insightand
intographics
the power
of Python
and the
to put
to work.events the
various graphics components publish, and we got some firsthand experience of the order in which events take
place. We prototyped a FrameEvents class that allowed us to see the runtime behavior of many events. With
prototyping it's much easier to see how events work.

777

We dealt with the basic


drawing
of shapes and
thethe
XORJava
graphics
mode
for rubberbanding.
were able to put
Python
Programming
with
Class
Libraries:
A Tutorial We
for Building
together the things we
learned
about graphics
programming
andJython
events in a very simple drawing application,
Web
and Enterprise
Applications
with
which we extended to
ideas in earlier chapters about object-oriented programming and the dynamic
Byincorporate
Richard Hightower
behavior of Jython.
Publisher: Addison Wesley
Pub Date: June 28, 2002 CONTENTS

Table of
Contents

ISBN: 0-201-61616-5
Pages: 640

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
Object-oriented programming concepts
File input/output
Python's intrinsic functions
Formatting, parsing, and manipulating strings
Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs
Working with SQL and JDBC(TM)
Python and Java applets
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
CONTENTS
Web and Enterprise Applications with Jython
By Richard Hightower

Chapter 16. Advanced


Swing
Publisher: Addison Wesley
Pub Date: June 28, 2002

JTable
ISBN: 0-201-61616-5
Table of
Working with Table
Models
Pages:
640
Contents
Putting Things TogetherAdding a Table Model to the Address Book Application
Characterized by ease of use, richness of expression, and concise syntax, Python has
JTree
remained a premier programming language for more than a decade, and is used by
JToolBar and
Actions
novices and professionals alike. In particular, its close relationship to Java(TM) makes
Summary the two languages, when used in combination, ideal for Web and distributed enterprise

application development.
Terms in This Chapter
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty
of method
skill-building exercises and interactive
sessions, this book will
Abstract
Helperprogramming
method
help those new to programming develop an understanding of concepts and practical
techniques.
For experienced programmers,Key/value
the book demonstrates
Python's breadth of
Array
pair
capabilities and shows the ways that Python interfaces with Java APIs for professional
Data modeldevelopment.
Main module
application
Design Programming
pattern
Object
wrapperA Tutorial for Building Web
Python
with the Java(TM) Class
Libraries:
and Enterprise Applications with Jython covers important topics such as:
Event listening
Self-documentation
Functional
decomposition
model/node
Fundamental
programming concepts,Tree
including
statements, expressions,
interpreters, and compilers
Hashtable
Python basics, including operators, string formatting, namespaces, classes, errors,
Our coverage of Swing so and
far has
focused on its differences from, and advantages over, AWT. But Swing is
exceptions
more than that. For example, it has some powerful GUI components, particularly JTable and JTree.
JTable shows data in a table
view, as in programming
a spreadsheet;concepts
JTree displays data in a hierarchical view, as in
Object-oriented
Microsoft Windows Explorer.
File input/output
In this chapter, we'll update the address book program, making it a JFC application that uses JTable. As we
Python's
functions
do this, we'll introduce other
Swingintrinsic
components.

JTable

Formatting, parsing, and manipulating strings

Interfacing with the Java APIs and working with Java Streams
To start out, we'll create a prototype that introduces the key features of JTable. Then we'll add JTable
Using Python
and the
Javaapplication
Swing to create
GUIs
support to the address application.
This time
will use
the MVC architecturethe
AddressBook class instance will be a model for the table.
Working with SQL and JDBC(TM)
We'll begin by creating a 4-by-4 grid, but first let's learn to use the JTable component. As always, follow
Python and Java applets
along in the interactive interpreter.

In addition, the book contains instructions for downloading and installing the Python
Import the JFrame and JTable classes from the javax.swing package.
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerousimport
code samples
make this JTable
book a useful learning experience.
>>> from javax.swing
JFrame,
youtoare
a sophisticated
computer user new to programming or a serious
Create an instance ofWhether
JFrame
hold
the table.
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into theexample')
power of Python and the know-how to put it to work.
>>> frame = JFrame('JTable
Create an instance of JTable, passing the number of rows and columns to its constructor. Then add the table
to the frame.

777

>>> table = JTable(4,4)


Python Programming with the Java Class Libraries: A Tutorial for Building
>>> frame.contentPane.add(table)
Web and Enterprise Applications with Jython
javax.swing.JTable[,0,0,0x0,invalid,alignmentX=null,alignmentY=null,border=,f
By Richard Hightower
s=32,maximumSize=,minimumSize=,preferredSize=,autoCreateColumnsFromModel=true
autoResizeMode=AUTO_RESIZE_SUBSEQUENT_COLUMNS,cellSelectionEnabled=false,
Publisher: Addison Wesley
editing...
Pub Date: June 28, 2002
...
ISBN: 0-201-61616-5

Table of

Pages: 640

Contents
Pack the
table in the frame, and show the frame.

Characterized by ease of use, richness of expression, and concise syntax, Python has
>>> frame.pack()
remained=a premier
programming language for more than a decade, and is used by
>>> frame.visible
1

novices and professionals alike. In particular, its close relationship to Java(TM) makes
thetyping
two languages,
used
in combination,
ideal
Web
andasdistributed
enterprise
Select a cell, and start
if you wantwhen
to. The
typed
text will show
up for
in the
cell,
illustrated in
Figure 16-1.
application development.
Figure 16-1. Cells with Text Entered
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise
The Default Table
ModelApplications with Jython covers important topics such as:
We didn't specify a model, so a default was provided in which the actual table data is kept. Here's how to access
Fundamental programming concepts, including statements, expressions,
that data.
interpreters, and compilers
Get the first row.

Python basics, including operators, string formatting, namespaces, classes, errors,


and exceptions
>>> table.model.dataVector[0]

[Hello, World, Its, good]

Object-oriented programming concepts

Get the first row, second column.


File input/output

>>> table.model.dataVector[0][1]
Python's intrinsic functions
'World'
Formatting, parsing, and manipulating strings
Get the first row, first column.
Interfacing with the Java APIs and working with Java Streams

>>> table.model.dataVector[0][0]
'Hello'
Using Python and Java Swing to create GUIs

This method is only guaranteed


to work
theand
default.
I use it to acclimate you to the model concepts first
Working
withfor
SQL
JDBC(TM)
introduced in Chapter 14, on JList.
Python and Java applets
Other forms of the JTable constructor allow you to pass in the initial values, that is, the row and column data.
Here's an example. In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
Create the row data. and numerous code samples make this book a useful learning experience.

>>> rowData =Whether


[ ['Marhta','Pena'],['Missy','Car'],
['Miguel','TorreAlto']
]
you are a sophisticated computer user new to programming
or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
Create the column headers.
give you insight into the power of Python and the know-how to put it to work.

>>> columnNames = ['First name', 'Last name']

777

Create a table with the row data and column headers.

>>> table = JTable(rowData,columnNames)


Python Programming with the Java Class Libraries: A Tutorial for Building
>>> frame.contentPane.add(table)
Web and Enterprise Applications with Jython
javax.swing.JTable[,0,0,0x0,invalid,alignmentX=null,alignmentY=null,border=,
By Richard Hightower
flags=32,maximumSize=,minimumSize=,preferredSize=,autoCreateColumnsFromModel=
autoResizeMode=AUTO_RESIZE_SUBSEQUENT_COLUMNS,cellSelectionEnabled=false,edit
Publisher: Addison Wesley
Column=-1,editingRow=1,gridColor=javax.swing.plaf.ColorUIResource[r=153,g=153
Pub Date: June 28, 2002
...
ISBN: 0-201-61616-5

Table of

Pages: 640

Contents
Pack the
table, and display it.

Characterized by ease of use, richness of expression, and concise syntax, Python has
>>> frame.pack()
remained a premier programming language for more than a decade, and is used by
>>> frame.visible=1

novices and professionals alike. In particular, its close relationship to Java(TM) makes
languages,
when
used
in combination,
ideal
and distributed
enterprise
There are other waysthe
to two
set the
initial data.
Later
we'll
cover the ones
thatfor
areWeb
substantially
different,
as well as a
application
development.
special method of populating a table with data using MVC.
This tutorial begins with coverage of some of the basics of Python programming. Using

Getting and Setting


Values
plenty of Table
skill-building
exercises and interactive programming sessions, this book will

help those new to programming develop an understanding of concepts and practical


With the interface provided
by JTable
, you canprogrammers,
get and set table
values.
Once the data
is set, breadth
you can of
modify
techniques.
For experienced
the book
demonstrates
Python's
it with the setValueAt()
capabilitiesmethod.
and shows the ways that Python interfaces with Java APIs for professional
application development.

>>> table.setValueAt('Hightower', 0, 1)
>>> table.setValueAt('Hightower',
1, 1)
Python Programming with the Java(TM)
Class Libraries: A Tutorial for Building Web
>>> table.setValueAt('Pena',
and Enterprise Applications2,
with1)
Jython covers important topics such as:
However, the more correct way of accessing data is with getValueAt().
Fundamental programming concepts, including statements, expressions,
>>> table.getValueAt(0,0)
interpreters, and compilers

'Marhta'
Python basics, including operators, string formatting, namespaces, classes, errors,
Tables can work with object
of primitive typesBoolean, integer, float, and so forth. Here we set the
andwrappers
exceptions
second column's values to Boolean so that they look like Figure 16-2.
Object-oriented programming concepts
Figure 16-2. Example Table with the Second Column Set to Boolean Values
File input/output
Python's intrinsic functions
Formatting, parsing, and manipulating strings
Interfacing with the Java APIs and working with Java Streams

>>>
>>>
>>>
>>>

from java.lang
import
Boolean
Using
Python and
Java Swing to create GUIs
table.setValueAt(Boolean(1), 0, 1)
Working with SQL and JDBC(TM)
table.setValueAt(Boolean(0),
1, 1)
table.setValueAt(Boolean(1), 2, 1)

Python and Java applets


You may have noticed that our demo table doesn't show headers. I don't know why, but I suspect it's a bug in
In addition, we
thecan
book
instructions
downloading
and installing
Python
JDK v.1.2.1. As a workaround,
putcontains
the table
in a scroll for
pane
(JScrollPane
). You the
usually
do this
language
and
the
Java
Development
Kit
(JDK).
Terminology,
definitions,
explanations,
anyway, so there should be no problem. It wasn't necessary in earlier Swing versions.
and numerous code samples make this book a useful learning experience.
JList makes much use of JScrollPane, which adds scrolling to a list or table via the Decorator design
Whether you
are aetsophisticated
computer
user
new to (from
programming
or a serious
pattern (see Design Patterns,
Gamma
al., 1995). Here's
the last
example
JTable2.py)
with the missing
application
developer,
Python
Programming
with
the
Java(TM)
Class
Libraries will
headers restored.
give you insight into the power of Python and the know-how to put it to work.

from javax.swing import JFrame, JTable, JScrollPane

777

frame = JFrame('JTable example')


#Create row data.

rowData = [ ['Marhta','Pena'],['Missy','Car'],
['Miguel','TorreAlto']
]
Python Programming with the Java Class Libraries:
A Tutorial for Building
Web and Enterprise Applications with Jython

#CreateByRichard
column
headers.
Hightower
columnNames = ['First name', 'Last name']
Publisher: Addison Wesley

#Create aPubtable
with
the row data and the column headers.
Date: June
28, 2002
table = JTable(rowData,columnNames)
ISBN: 0-201-61616-5
Table of
frame.contentPane.add(JScrollPane(table))

Pages: 640
Contents

frame.pack() Characterized by ease of use, richness of expression, and concise syntax, Python has
frame.visibleremained
= 1 a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
Now the table should look like Figure 16-3.
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
Figure 16-3. Table with the Column Headers Restored
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

Working with Table Models


Fundamental programming concepts, including statements, expressions,
The most common way to create
tables and
is tocompilers
supply the data model first. JTable works with any class instance
interpreters,
that inherits from the TableModel interface (recall that a Java interface is like a Python class with all abstract
methods). Let's first see what
the TableModel
dostring
and then
create a namespaces,
short exampleclasses,
that uses
our old
Python
basics, includingmethods
operators,
formatting,
errors,
address book application. and exceptions
Object-oriented programming concepts
File input/output
Data

Model Review

Python's intrinsic functions


We've covered TableModel and JList, so I won't go into the same level of detail because
I'm assuming that you
did your reading
exercises and
now have a basic understanding of
Formatting,
parsing,and
andyour
manipulating
strings
them. If you don't, you may want to do a little review. You'll need it to understand the JTable
andJTree controls,
which willwith
be covered
Interfacing
the Javalater
APIson.
and working with Java Streams
Using Python and Java Swing to create GUIs

The TableModel Interface

Working with SQL and JDBC(TM)


TheTableModel interface is contained in javax.swing.table and specifies how table model data
Python
and JavaTableModel
applets
will be treated. Any class that
implements
can act as a data model for JTable.
In addition,
the book contains instructions for downloading and installing the Python
Here are TableModel
's methods:
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.

getRowCount()
Whether you are a sophisticated computer user new to programming or a serious

getColumnCount()
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

getColumnName(columnIndex)

777

getColumnClass(columnIndex)
isCellEditable(rowIndex, columnIndex)

Python Programming with the Java Class Libraries: A Tutorial for Building
getValueAt(rowIndex,
columnIndex)
Web and Enterprise Applications with Jython
By Richard Hightower

setValueAt(rowIndex, columnIndex)
Publisher: Addison Wesley
addTableModelListener(l)
Pub Date: June 28, 2002

removeTableModelListener(l)
ISBN: 0-201-61616-5

Table of

Pages: 640

Contents represents a tabular object just like a spreadsheet. Thus, getRowCount() and
TableModel
getColumnCount()
return the
of rows
and columns,
from which
the total
number
of cells
Characterized
bynumber
ease of use,
richness
of expression,
and concise
syntax,
Python
has can be

calculated (row count


* columna premier
count). You
can accesslanguage
the row for
andmore
column
as theand
properties
remained
programming
thancounts
a decade,
is used by
instance.columnCount
and
instance.rowCount
,
respectively.
novices and professionals alike. In particular, its close relationship to Java(TM) makes

the two languages, when used in combination, ideal for Web and distributed enterprise

setValueAt() and getValueAt() set and get cell data by specifying the cell's row and column
application development.
indexes. The isCellEditable() method determines if the cell is read-only or read/write. Many times
when using a table, you're
likely showing
a report
or some
otheroftype
staticofdata,
in which
case
This tutorial
begins with
coverage
of some
theof
basics
Python
programming.
Using
isCellEditable()
returns
false.
If
you're
changing
the
cell
data,
it
returns
true.
plenty of skill-building exercises and interactive programming sessions, this book will

help those new to programming develop an understanding of concepts and practical


techniques. For experienced programmers, the book demonstrates Python's breadth of
that the column deals with, which helps in displaying and editing the column's cells, as we'll see later.
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
addTableModelListener()
and removeTableModelListener() allow components like

getColumnName(), obviously, returns the name of a column. getColumnClass() returns the class

JTable instances to register for TableModel events.

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

The AbstractDataModel Class

concepts,
including
statements,
expressions,
Firing events and tracking Fundamental
event listenersprogramming
can be real but
necessary
annoyances.
Wouldn't
it be nice, though, if all
compilers
of their functionality was ininterpreters,
a common,and
extensible
class? This is where object-oriented programming comes in.
Our friends at JavaSoft have combined event firing and listener tracking in a class called
basics, including operators, string formatting, namespaces, classes, errors,
AbstractDataModelPython
.
and exceptions
AbstractDataModel is, obviously, abstract, so you have to instantiate it in a subclass (i.e., extend it). It
concepts
makes no assumption aboutObject-oriented
how you supplyprogramming
or define your
data, so you don't get the getRowCount(),
getColumnCount(),File
or getValueAt() methods with it. That's okay, because
input/output
DefaultDataModel, which does have them, extends AbstractDataModel.
Python's intrinsic functions
Remember when we initialized a JTable with no model, just data? JTable took that data and passed it to an
instance of DefaultDataModel
other and
words,
even whenstrings
we don't pass JTable a model, it still uses
Formatting,. In
parsing,
manipulating
one, or rather it uses an instance of a class that implements the TableModel interface.
Interfacing with the Java APIs and working with Java Streams
To show how AbstractDataModel works, we'll go back to our pizza topping application, but this time
we'll add editable columns Using
and Boolean
The
first column
list the toppings; the second will hold
Python values.
and Java
Swing
to createwill
GUIs
checkboxes that are set when the customer makes a selection.
Working with SQL and JDBC(TM)
Here's the complete topping code (model.py):
Python and Java applets

from javax.swing.table import AbstractTableModel


In addition,
the book
contains instructions
from java.lang
import
Boolean,
String for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
class PizzaTableModel(AbstractTableModel):
Whether you are a sophisticated computer user new to programming or a serious
def __init__(self):
application developer,
Python Programming with
the Java(TM) Class Libraries will
self.data
= [ ['Pepperoni',
Boolean(0)],
give you insight into ['Sausage',
the power of PythonBoolean(0)],
and the know-how to put it to work.
['Onions', Boolean(0)],
['Olives', Boolean(0)],
['Mushrooms', Boolean(0)],
['Peppers', Boolean(0)] ]

777

self.columnNames
= the
['Topping',
'Add?']
Python Programming with
Java Class Libraries:
A Tutorial for Building
self.columnClasses
= [String,
Boolean]
Web and Enterprise Applications
with Jython
self.Add=1
By Richard Hightower
def getRowCount(self):
Publisher: Addison Wesley
return
len(self.data)
Pub Date:
June 28, 2002

Table
of
def
Contents

ISBN: 0-201-61616-5

getColumnCount(self):
Pages: 640
return len(self.data[0])
Characterized by ease of use, richness of expression, and concise syntax, Python has

def getValueAt(self,
rowIndex,
columnIndex):
remained a premier programming
language
for more than a decade, and is used by
return
self.data[rowIndex][columnIndex]
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise

def getColumnName(self,
columnIndex):
application development.
return self.columnNames[columnIndex]
def getColumnClass(self,
columnIndex):
This tutorial begins with coverage
of some of the basics of Python programming. Using
return
self.columnClasses[columnIndex]
plenty of skill-building
exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical

def isCellEditable(self,
rowIndex,
columnIndex):
techniques. For experienced programmers,
the book
demonstrates Python's breadth of
return
capabilitiescolumnIndex
and shows the ways==
thatself.Add
Python interfaces with Java APIs for professional
application development.

def setValueAt (self, value, rowIndex, columnIndex):


Python Programming with
Java(TM) Class Libraries: A Tutorial for Building Web
if(columnIndex
==theself.Add):
and Enterprise
Applications
with Jython covers important topics such as:
value
= Boolean(value)
self.data[rowIndex][columnIndex] = value
self.fireTableCellUpdated(rowIndex, columnIndex)
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers

A Table Model for the Pizza Topping ApplicationStep by Step

Python basics, including operators, string formatting, namespaces, classes, errors,


First we import the classes and
we exceptions
need: AbstractTableModel and PizzaTableModel (which extends
AbstractTableModel).PizzaTableModel provides the user interface. It also imports the
Object-oriented
concepts
Boolean and String classes,
which itprogramming
uses for the getColumnClass()
method (more on this later).
File input/output
from javax.swing.table
import AbstractTableModel
from java.lang import Boolean, String
Python's intrinsic functions

class PizzaTableModel(AbstractTableModel):

Formatting, parsing, and manipulating strings

Next the PizzaTableModel constructor defines three variables: data, which holds the cell data in a list
Interfacing with the Java APIs and working with Java Streams
of lists; columnNames, which holds the column headers in a list of strings; and columnClasses, which
holds the classes in a list ofUsing
classes.
It also
defines
a variablea
Python
and
Java Swing
to createconstant
GUIs that defines the location of the Add?
column. Add? consists of Boolean values that determine whether or not a customer selects a particular topping.
Working with SQL and JDBC(TM)

def __init__(self):
self.data =Python
[ ['Pepperoni',
Boolean(0)],
and Java applets
['Sausage', Boolean(0)],
In addition,['Onions',
the book containsBoolean(0)],
instructions for downloading and installing the Python
language and
the Java Development
Kit (JDK). Terminology, definitions, explanations,
['Olives',
Boolean(0)],
and numerous
code samples makeBoolean(0)],
this book a useful learning experience.
['Mushrooms',
['Peppers', Boolean(0)] ]
Whether you are a=sophisticated
computer
user new to programming or a serious
self.columnNames
['Topping',
'Add?']
application developer,
Programming
with the Java(TM) Class Libraries will
self.columnClasses
= Python
[String,
Boolean]
give
you
insight
into
the
power
of
Python
and
the know-how to put it to work.
self.Add=1
PizzaTableModel implements getRowCount() by returning the length of the data list.

777

def getRowCount(self):

return Python
len(self.data)
Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython

It also implements getColumnCount()


by returning the length of the first list in the data variable. Recall
By Richard Hightower
thatdata is a list of lists and that all of the lists contain two items.
Publisher: Addison Wesley

def getColumnCount(self):
Pub Date: June 28, 2002
return len(self.data[0])

ISBN: 0-201-61616-5
Table of

Pages:
640and columns of
getValueAt()
indexes the rows
Contents

data's list of lists and returns

def getValueAt(self,
columnIndex):
Characterized rowIndex,
by ease of use, richness
of expression, and concise syntax, Python has
return remained
self.data[rowIndex][columnIndex]
a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes

getColumnNames()
the columnNames
list with the
columnIndex
argumententerprise
and returns
the twoindexes
languages,
when used in combination,
ideal
for Web and distributed
application development.

def getColumnName(self, columnIndex):


return This
self.columnNames[columnIndex]
tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will

getColumnClass()
returns
that results
from indexing
columnClasses
. The
class it returns
help those
newthe
to value
programming
develop
an understanding
of concepts and
practical
determines the cell editor
JTable
will
use.
Setting
the
second
column
to
Boolean
values
converts
it toof
techniques. For experienced programmers, the book demonstrates Python's breadth
checkboxes.

capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.

def getColumnClass(self, columnIndex):


return Python
self.columnClasses[columnIndex]
Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

isCellEditable() helps JTable determine if the cell can be modified. Every cell in Add? is editable,
so for that column a true value is returned. Remember, the Add attribute is a constant that denotes the Add?
column.

Fundamental programming concepts, including statements, expressions,


interpreters, and compilers

def isCellEditable(self, rowIndex, columnIndex):


return columnIndex
self.Add
Python basics, ==
including
operators, string formatting, namespaces, classes, errors,
and exceptions

setValueAt() sets the value of the Add? column only. It should never be called for the Toppings column
unless the JTable instance
has determined,
through isCellEditable()
, that it can be modified. For
Object-oriented
programming
concepts
this reason, setValueAt() checks if the column index is Add? If so, it converts the set value to Boolean.
File input/output
Remember that Python treats Boolean primitives as integers, so we convert the set value to Boolean. Then we
indexdata with the rowIndex
columnIndex
arguments, set the data's value, and notify all event
Python's and
intrinsic
functions
listeners of the change via fireTableCell().
Formatting, parsing, and manipulating strings
AbstractTableModel implements fireTableCell() along with other helper methods like
Interfacing with
the Java APIs and working with Java Streams
addTableModelListener()
and removeTableModelListener()
.
Using Python
and Java
Swing to create
GUIs
def setValueAt (self,
value,
rowIndex,
columnIndex):
if(columnIndex == self.Add):
Working
with SQL and JDBC(TM)
value
= Boolean(value)
self.data[rowIndex][columnIndex] = value
Python and Java applets
self.fireTableCellUpdated(rowIndex, columnIndex)
In addition, the book contains instructions for downloading and installing the Python
To test the model at this point we add the following code, but only if model.py is run as the main module.
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous
code samples make this book a useful learning experience.
if __name__ ==
'__main__':

from javax.swing import JTable, JFrame, JScrollPane


Whether you are a sophisticated computer user new to programming or a serious
pizza_model = PizzaTableModel()
application developer, Python Programming with the Java(TM) Class Libraries will
table = JTable(pizza_model)
give you insight into the power of Python and the know-how to put it to work.
frame = JFrame('Select your toppings')
frame.contentPane.add(JScrollPane(table))
frame.pack()
frame.visible = 1

777

The first part of the code


imports
JTable,JFrame
and JScrollPane
. Then
it creates
table and a
Python
Programming
with the, Java
Class Libraries:
A Tutorial
fora Building
frame and passes theWeb
tableand
to a Enterprise
JScrollPane
constructor,
Applications
with adding
Jythonthe JScrollPane instance to the
frame's content pane.ByFinally
it Hightower
packs the frame and makes it visible.
Richard
Runmodel.py. What youPublisher:
get shouldAddison
look like
Figure 16-4. Then try these exercises:
Wesley
Pub Date: June 28, 2002

Add five
Table
of
Contents

ISBN: 0-201-61616-5
more toppings.
Pages: 640

Add a column called Extra for the customer to choose an extra amount of a particular topping. Make it so
Characterized
ease
of use, richness
of the
expression,
and concise
syntax, Python has
the cells can be
edited only ifbythe
corresponding
cell in
Add? column
is selected.
remained a premier programming language for more than a decade, and is used by
novices and professionals
alike. The
In particular,
its Table
close relationship to Java(TM) makes
Figure 16-4.
Topping
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.

This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
Fundamental programming concepts,
includingModel
statements,to
expressions,
Putting Things TogetherAdding
a Table
the Address
interpreters, and compilers
Book Application
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
In this section, we'll add a table
model to the address book application and "swingify" some of the application's
AWT ways.

Object-oriented programming concepts


File input/output

AWT
Python's intrinsic functions

to JFC

Formatting,
and manipulating
strings
The first time I wrote
the addressparsing,
book application,
I used all
of the old AWT components
(java.awt.Frame,java.awt.Panel, etc.). When I modified it, only 12 lines out of 114
Interfacing
with
the with
Java JList
APIs and
had to be changed, and
9 of those
dealt
. working with Java Streams
and Java
Swing to
create GUIs
The point is that theUsing
move Python
from List
to JList
changed
a lot, although most of the changes
weren't needed. Other JFC/AWT components map nicely even though they're not closely related on
with SQL
andexception,
JDBC(TM)
the class hierarchy. Working
Luckily, JList
is the
not the rule.
Python
Java appletsis pretty much the same as AWT. Most developers have
Up to now what we've
seenand
of JFC/Swing
migrated to Swing by now, in spite of the fact that the first few Swing versions were well short of
In addition, the book contains instructions for downloading and installing the Python
perfect. Since then, Swing has proven its worth.
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.

Adding a Table and Moving the Address Data to a View

Whether you are a sophisticated computer user new to programming or a serious


application developer, Python Programming with the Java(TM) Class Libraries will
Now it's time to start tinkering with our "swingified" address book application, first adding support for a table.
give you insight into the power of Python and the know-how to put it to work.
To do this we'll move the address data to a model, which will be a combination table and list. The purpose is to
show how, with MVC, many views can be updated from a single data source.

777

Recall from prior examples that the address data was loaded into a dictionary (dict) from a file. We'll use this
dictionary to hold the addresses, as always, but instead of making dict an aggregate member of

AddressMain, we'll
create
a new class called
that acts as
a listfor
model
and a table
Python
Programming
with AddressModel
the Java Class Libraries:
A both
Tutorial
Building
model and put dictWeb
in there.
Then we'll add
a JFC tablewith
to theJython
class so that both the JList and JTable
and Enterprise
Applications
instances reference the
same modelthat
By Richard
Hightower is, an AddressMain instance.
The tricky part of AddressMain
is mapping the address data (stored in a dictionary) to both the list and table
Publisher: Addison Wesley
models. We'll accomplish
this by creating a Python list to contain the sorted dictionary keys, which we'll use to
Pub Date: June 28, 2002
sort the addresses by name into table rows. This will make it easier to get the address instance at a given row
ISBN: 0-201-61616-5
Table of
index.

Contents

Pages: 640

ForAddressModel to act as a model for both a list and a table, it needs to implement the ListModel and
Characterized
by earlier,
ease of JFC
use, provides
richness of
expression, and concise syntax,
TableModel interfaces.
As I said
AbstractListModel
and Python has
remained
a
premier
programming
language
for
more
than
a
decade,
is used by
AbstractTableModel classes that hold a good part of the functionality needed toand
implement
their
novices
and
professionals
alike.
In
particular,
its
close
relationship
to
Java(TM)
makes
respective models. We want to use them, but we can't just inherit their functionality. In Java you can't extend two
languages,
when
used in combination,
Webtwo
andJava
distributed
enterprise
base classes, but youthe
cantwo
implement
many
interfaces.
In Jython youideal
can't for
extend
base classes,
but you
application
development.
can extend two Python base classes. To overcome this obstacle, what we have to do is extend from
AbstractTableModel and implement AbstractListModel's interface.
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
AddressModelhelp those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
The following code (from
Two/AddressModel.py)
shows
's definition
capabilities
and shows the ways
that AddressModel
Python interfaces with
Java APIsand
forconstructor.
professionalNotice
thatAddressModel
implements
TableModel
(through
AbstractTableModel
)
and
application development.
ListModel.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
class AddressModel(AbstractTableModel,
ListModel):
and Enterprise Applications with Jython covers
important topics such as:

"""The AddressModel is both a ListModel and a TableModel."""


def __init__(self):
Fundamental programming
concepts, model.
including statements, expressions,
"""Initialize
the Address
and compilers from the file."""
Readinterpreters,
the dictionary
Python basics, including operators, string formatting, namespaces, classes, errors,

self.dict = None
and exceptions
self.list = None

# holds the dictionary of addresses.


# holds the sorted list of names,
# concepts
which are keys
Object-oriented programming
# into the dictionary.
File input/output

self.listeners = [] #to hold list of ListModelListeners


Python's intrinsic functions

# Read the addresses from the file.


Formatting, parsing, and manipulating strings # holds the file name
self.fname=".\\addr.dat"
# that holds the addresses
Interfacing =
with
the Java APIs and working with Java Streams
self.dict
readAddresses(self.fname)
Using Python and Java Swing to create GUIs

# Store the sorted list of names.


self.list
= self.dict.keys()
Working with
SQL and JDBC(TM)
self.list.sort()
Python and Java applets

# Define the column names and locations in the table.

Inself.columnNames=['Name',
addition, the book contains instructions for
downloading
installing the Python
'Phone
#',and
'Email']
language
and the Java
Kit (JDK).
self.NAME
= 0 Development
# To hold
theTerminology,
locationdefinitions,
of theexplanations,
name column
and
numerous code=samples
this book
a useful
learning experience.
self.PHONE
1 # make
To hold
the
location
of the phone number column

self.EMAIL = 2

# To hold the location of the email column

Whether you are a sophisticated computer user new to programming or a serious


application
Python
Programming
with the Java(TM)
Class
Libraries
will
We can see that the list
is sorteddeveloper,
and that the
rows in
the table correspond
to the index
values
of the sorted
you insight
into
of Python
the of
know-how
to work.
names. Thus, a givengive
address
is stored
in the power
table based
on theand
index
the nameto
input
theitlist.
For the columns,
we need to be more creative. The constants defined in the constructor correspond to the placement of the
address instance fields in the rows relative to the columns.

777

AddressModel's Helper Methods

Python Programming with the Java Class Libraries: A Tutorial for Building

To map the address dictionary


(self.dict
) in the AddressModel
interface to a table, we need to define
Web and Enterprise
Applications
with Jython
some helper methods,
shownHightower
in the following code (Two\AddressModel.py). The method names are selfByas
Richard
explanatory, and the comments should fill in any blanks. (Make sure to read the comments and document strings;
think of them as integralPublisher:
to the concepts
in Wesley
this chapter.)
Addison
Pub Date: June 28, 2002

def __getAddressAtRow(self, rowIndex):


ISBN: 0-201-61616-5
Table of """Get the address at the specified row.

Pages: 640
Contents
(Private methods begin with __)"""
Characterized by ease of use, richness of expression, and concise syntax, Python has
# Get the row name out of the list.
remained a premier programming language for more than a decade, and is used by
# Use the name to index the dictionary of addresses.
novices and professionals alike. In particular, its close relationship to Java(TM) makes
# Get the address associated with this row.
the two languages, when used in combination, ideal for Web and distributed enterprise
name = self.list[rowIndex]
application development.

address = self.dict[name]
return
address
This tutorial
begins with coverage of some of the basics of Python programming. Using
def __getAddressAttributeAtColumn(self,
address,
columnIndex):
plenty of skill-building exercises and interactive
programming
sessions, this book will
"""Get
the
attribute
of
the
address
at
the
help those new to programming develop an understanding of concepts and practical
specified
columnprogrammers,
index. Maps
column
indexes
techniques.
For experienced
the book
demonstrates
Python's to
breadth of
attributes
ofthethe
class with
instances."""
capabilities
and shows
ways address
that Python interfaces
Java APIs for professional
application development.

value = None # Holds the value we are going to return


Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
# Set
the value
based
onimportant
the column
and Enterprise
Applications
with Jython
covers
topics suchindex.
as:

if(columnIndex == self.NAME):
value = address.name()
Fundamental programming concepts, including statements, expressions,
interpreters,
and compilers
Mapping to ListModel and
TableModel
Python basics, including operators, string formatting, namespaces, classes, errors,
The first two helper methods map the list and name attributes to ListModel and the dict and
and exceptions
address instances to TableModel.getAddressAtRow() gets the address at the specified row.
getAddressAttributeAtColumn()
gets the address
Object-oriented programming
concepts attribute at the specified column index; that
is, it maps column indexes to attributes of the address instances. Since the name attribute is used to
determine the row index, __changeDictKey()
and __changeList() keep the list and dictionary in
File input/output
sync with each address whose name attribute is changed.
Python's intrinsic functions
Formatting, parsing, and manipulating strings

Comments: More Is More

Interfacing with the Java APIs and working with Java Streams
Sometimes I comment
the Python
obviousand
in my
buttowhen
it comes
Using
Javacode,
Swing
create
GUIs to comments I don't believe that
less is more. In fact, when things aren't obvious, such as mapping a dictionary to a table model, I
prefer to go overboard.
Working with SQL and JDBC(TM)
Don't be chintzy with
your comments.
For every minute saved by not writing them, you'll waste a
Python
and Java applets
hundred minutes in code maintenance.
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.

Whether you are a sophisticated computer user new to programming or a serious


application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

Stupid Methods

Most of the timePublisher:


you break Addison
methodsWesley
into many other methods so that the same code isn't repeated
Pub
Date:
June
2002
in different places.
This
is an
idea28,
borrowed
from functional decomposition. In object-oriented
programming, there'sISBN:
another
reason to do this. It's called stupid, and that's a good thing.
0-201-61616-5

Table of
Contents

Pages: 640

Keep your methods short and stupid. Long methods are hard to understand and hard to change, so
you have to divide
to conquer.
is a stupid
Characterized
by __setAddressAttributeAtColumn()
ease of use, richness of expression, and concise syntax,
Python has
method because
it's called
by onlyprogramming
one other method,
leaving
functional
ofby
the
remained
a premier
language
for more
than adecomposition
decade, and isout
used
picture.
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
Implementing theapplication
ListModeldevelopment.
Interface

This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
def getSize(self):
techniques.
experienced
the book
demonstrates
Python's breadth of
"""Returns
theForlength
ofprogrammers,
the items
in the
list."""
capabilities
and
shows
the
ways
that
Python
interfaces
with
Java
APIs
for professional
return len(self.list)
application development.

AddressModel's next four methods implement the ListModel interface.

def getElementAt(self, index):


Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
""" Returns the value at index. """
and Enterprise Applications with Jython covers important topics such as:
return self.list[index]
def addListDataListener(self,
l): concepts, including statements, expressions,
Fundamental programming
"""Add a listener
that's
notified when the model changes."""
interpreters, and compilers
self.listeners.append(l)
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
def removeListDataListener(self,
l):
"""Remove a listener."""
Object-oriented programming concepts
self.listeners.remove(l)
File input/output
getSize() returns the length
of the list attribute. (Remember that list consists of the sorted keys of the
dict attribute, and name corresponds to the address stored at the location indicated by the key.)
Python's
intrinsicatfunctions
getElementAt() returns
the element
the index from the list. addListDataListener() and
removeListDataListener()
keep track of the listeners that subscribe to events from
Formatting, parsing, and manipulating strings
AddressModel instances.
Interfacing with the Java APIs and working with Java Streams
ListModel Event Notification
Using Python and Java Swing to create GUIs
Every time a ListModel event occurs, AddressModel notifies the listeners that have subscribed to it
Working with SQL and JDBC(TM)
using the following methods:
Python and Java applets index, index1):
def __fireContentsChanged(self,
"""Fire contents changed, notify viewers
In addition, the book contains instructions for downloading and installing the Python
that the list changed."""
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
event = ListDataEvent(self, ListDataEvent.CONTENTS_CHANGED, index,
and numerous code samples make this book a useful learning experience.
index1)
Whether you are a sophisticated computer user new to programming or a serious

for
listener
in Python
self.listeners:
application
developer,
Programming with the Java(TM) Class Libraries will
listener.contentsChanged(event)
give you insight into the power of Python and the know-how to put it to work.
def __fireIntervalAdded(self, index, index1):
"""Fire interval added, notify viewers
that the items were added to the list."""

777

event Python
= ListDataEvent(self,
ListDataEvent.INTERVAL_ADDED,
Programming with the Java
Class Libraries: A Tutorial for Building index,
Webindex1)
and Enterprise Applications with Jython
By Richard Hightower

for listener in self.listeners:


listener.intervalAdded(event)
Publisher:
Addison Wesley
Pub Date: June 28, 2002

def __fireIntervalRemoved(self,
index, index1):
ISBN: 0-201-61616-5
Table """Fire
of
interval
removed
from the list,

Pages: 640
Contents
notify viewers."""
Characterized by ease of use, richness of expression, and concise syntax, Python has

event
= aListDataEvent(self,
ListDataEvent.INTERVAL_REMOVED,
index,
remained
premier programming language for
more than a decade, and is used by
index1)
novices and professionals alike. In particular, its close relationship to Java(TM) makes
for
listener
the two
languages, in
whenself.listeners:
used in combination, ideal for Web and distributed enterprise
listener.intervalRemoved(event)
application
development.
Implementing theThis
TableModel
Interface
tutorial begins
with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
helphelp
thoseimplement
new to programming
develop an
understanding
concepts the
and practical
The next set of methods
the TableModel
interface,
partly byofextending
techniques.
For
experienced
programmers,
the
book
demonstrates
Python's
of and
AbstractTableModel class and partly by mapping the addresses stored in the dictionary breadth
to the rows
capabilities
and
shows
the
ways
that
Python
interfaces
with
Java
APIs
for
professional
columns in the table model.
application development.

## The following methods implement the TableModel interface. ##


Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers
important topics such as:
def addTableModelListener(self,
l):
"""Add a listener that gets notified when the data model
changes. Since all we are doing is calling the super,
Fundamental
concepts,
including statements, expressions,
we don'tprogramming
need this
method."""
interpreters, and compilers
AbstractTableModel.addTableModelListener(self,
l)
Python basics, including operators, string formatting, namespaces, classes, errors,

def removeTableModelListener(self,
l):
and exceptions
"""Remove a listener. Since all we are doing is
calling programming
the super,
we don't need this method.
Object-oriented
concepts
It's here for example."""
AbstractTableModel.removeTableModelListener(self,
l)
File input/output
Python's intrinsic functions columnIndex):
def getColumnClass(self,
"""Returns the common base Class for the column."""
Formatting,
parsing, and manipulating strings
return
String
def getColumnCount(self):
Interfacing with the Java APIs and working with Java Streams
"""Returns the number of columns in the data model."""
return
len(self.columnNames)
Using Python
and Java Swing to create GUIs

def getColumnName(self,
columnIndex):
Working with SQL and JDBC(TM)
"""Returns the name of the given column by columnIndex."""
return
self.columnNames[columnIndex]
Python and
Java applets
In addition, the book contains instructions for downloading and installing the Python
def getRowCount(self):
language
and the Java the
Development
Kit of
(JDK).
Terminology,
"""Returns
number
rows
in thedefinitions,
table explanations,
model."""
and numerous
code
samples
make
this
book
a
useful
learning
experience.
return len(self.list)
Whether you are a sophisticated
computer user
new to programming or a serious
def getValueAt(self,
rowIndex,
columnIndex):
application
developer,
Python
Programming
with
Java(TM) Class
Libraries will
"""Returns the cell value atthelocation
specified
give you insight
into
the
power
of
Python
and
the
know-how
to
put
it
to
work.
by columnIndex and rowIndex."""

777

# Get the address object corresponding to this row.


address = self.__getAddressAtRow(rowIndex)

# Get
the
corresponding
Python Programming
with
the address
Java Classattribute
Libraries: A Tutorial
for Building
# to
this column.
Web and Enterprise
Applications
with Jython
value
= self.__getAddressAttributeAtColumn(address,
By Richard
Hightower

columnInde

returnAddison
value
Publisher:
Wesley
Pub Date: June 28, 2002

def isCellEditable(self,
rowIndex, columnIndex):
ISBN: 0-201-61616-5
Table of
"""Returns
if
the
cell is editable at the given
Pages: 640
Contents
rowIndex and columnIndex."""
Characterized by ease of use, richness of expression, and concise syntax, Python has
are language
editable
remained a#All
premiercells
programming
for more than a decade, and is used by
return
1
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
def setValueAt(self,
application development. aValue, rowIndex, columnIndex):

"""Sets the value for the cell at the given

andof rowIndex."""
This tutorialcolumnIndex
begins with coverage
some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
Get the develop
address
object corresponding
to this row.
help those new to#programming
an understanding
of concepts and practical
address
= self.__getAddressAtRow(rowIndex)
techniques.
For experienced
programmers, the book demonstrates Python's breadth of
self.__setAddressAttributeAtColumn(aValue,
address, columnInde
capabilities
and shows the ways that Python interfaces with Java APIs for professional
self.fireTableCellUpdated(rowIndex,
columnIndex)
application development.
addTableModelListener()
and with
removeTableModelListener()
are for
in the
code for
Python Programming
the Java(TM) Class Libraries: A Tutorial
Building
Web
illustration only, because
AbstractTableModel
already
implements
them.
Thissuch
means
and Enterprise
Applications with Jython
covers
important
topics
as: that the following
code is unnecessary:

Fundamental programmingl):
concepts, including statements, expressions,
def addTableModelListener(self,
interpreters, and compilers
...
...
Python basics, including operators, string formatting, namespaces,
classes, errors,
AbstractTableModel.addTableModelListener(self,
l)
and exceptions

def removeTableModelListener(self, l):


Object-oriented programming concepts
...
...
File input/output
AbstractTableModel.removeTableModelListener(self, l)
Python's intrinsic functions
Columns and Rows

Formatting, parsing, and manipulating strings

AddressModel inherits functionality from AbstractTableModel, so we can leave out


Interfacing with
the Java APIs and working with Java Streams
addTableModelListener()
and removeTableModelListener()
(that's what we'll do in the
third iteration of this example), and it will still function.
Using Python and Java Swing to create GUIs
Here are three methods that work with columns:
Working with SQL and JDBC(TM)

def getColumnClass(self, columnIndex):


Python and Java applets
"""Returns the common base Class for the column."""
return
String
In addition,
the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,

def getColumnCount(self):
and numerous code samples make this book a useful learning experience.
"""Returns the number of columns in the data model."""
return
len(self.columnNames)
Whether
you are a sophisticated computer user new to programming or a serious

application developer, Python Programming with the Java(TM) Class Libraries will

def getColumnName(self,
give you insight intocolumnIndex):
the power of Python and the know-how to put it to work.
"""Returns the name of the given column
by columnIndex."""
return self.columnNames[columnIndex]

777

getColumnClass()
always
returns a string
every
attribute
we expose
in the AddressModel
Python
Programming
with because
the Java
Class
Libraries:
A Tutorial
for Building
class is a string. getColumnCount()
uses the lengthwith
of the
columnNames attribute (defined in
Web and Enterprise Applications
Jython
AddressModel'sByconstructor),
which is a list of strings that contain column names for the table model. It
Richard Hightower
also uses the column index (columnIndex) as an index into columnNames to get the name that
corresponds to a given column.
Publisher: Addison Wesley
Pub Date: June 28, 2002

Only one method deals with rows specifically, getRowCount(), which returns the length of the items in
ISBN: 0-201-61616-5
columnNames
. Every item in columnNames corresponds to a key that specifies a row in the table. This
Table of

Pages: 640
meansContents
that the length of columnNames is equal to the number of rows in TableModel.

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
The next three methods
get and
edit cells
in the
table.
the two
languages,
when
used
in combination, ideal for Web and distributed enterprise
application development.
Cell Values

def getValueAt(self, rowIndex, columnIndex):


"""Returns
thewith
cell
value
atof location
specified
by Using
This tutorial begins
coverage
of some
the basics of Python
programming.
columnIndex
and
rowIndex."""
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
Get
the address
object
this
techniques.#For
experienced
programmers,
the bookcorresponding
demonstrates Python's to
breadth
of row.
address
self.__getAddressAtRow(rowIndex)
capabilities=and
shows the ways that Python interfaces with Java APIs for professional
application development.

# Get the address attribute

# corresponding
to Class
this
column.
Python Programming
with the Java(TM)
Libraries:
A Tutorial for Building Web
value
= self.__getAddressAttributeAtColumn(address,
columnIndex)
and Enterprise
Applications with Jython covers important topics such as:
return value
Fundamental programming concepts, including statements, expressions,
interpreters, and
compilers
def isCellEditable(self,
rowIndex,
columnIndex):

"""Returns if the cell is editable at the given


Python basics, and
including
operators, string formatting, namespaces, classes, errors,
rowIndex
columnIndex."""
and exceptions
# All cells are editable
returnObject-oriented
1
programming concepts
def setValueAt(self, aValue, rowIndex, columnIndex):
"""Sets
the value for the cell at the given
File input/output
columnIndex and rowIndex."""
Python's intrinsic functions

# Get the address object corresponding to this row.


Formatting,
parsing, and manipulating strings
address
= self.__getAddressAtRow(rowIndex)
self.__setAddressAttributeAtColumn(aValue, address, columnIndex)
Interfacing with the Java APIs and working with Java
Streams
self.fireTableCellUpdated(rowIndex,
columnIndex)
Using Python and Java Swing to
to create
getValueAt() uses __getAddressAtRow()
get theGUIs
address at the current row; then it uses
__getAddressAttributeAtColumn() to get the value of the attribute corresponding to the given
Working with SQL and JDBC(TM)
column index, and returns the value received. (__getAddressAttributeAtColumn() is an example
of a stupid method: Its name
describes
whatapplets
it does, which makes it almost completely self-documenting.)
Python
and Java

IsCellEditable()
assumes
cells areinstructions
editable and
true (1)and
no matter
what
row index
In addition,
the that
bookallcontains
forreturns
downloading
installing
thethe
Python
and column index are
equal to.and the Java Development Kit (JDK). Terminology, definitions, explanations,
language

and numerous code samples make this book a useful learning experience.
LikegetValueAt(),setValueAt() uses __getAddressAtRow() to retrieve the address at the
given row index (making
getAddressAtRow()
a good example
decomposition).
Whether
you are a sophisticated computer
user newoftofunctional
programming
or a serious Next it uses
__setAddressAttribute()
to
set
the
value
of
the
address
attribute
corresponding
to the
column
application developer, Python Programming with the Java(TM) Class Libraries
will
index and, finally, notifies
every
JTable
view
of
the
change.
This
way,
if
multiple
views
are
listening
(or
give you insight into the power of Python and the know-how to put it to work.
using the same model), they'll all be updated.

777

__setAddressAttribute()

Because it does so much,


let'sProgramming
take a closer look
atthe
__setAddressAttribute()
. Examine
the code
Python
with
Java Class Libraries: A Tutorial
for Building
closely. If you understand
it, you
understand
AddressModel
.
Web and
Enterprise
Applications
with Jython
By Richard Hightower

def __setAddressAttributeAtColumn(self, value, address, columnIndex):


"""Sets
the address attribute at the corresponding
Publisher: Addison Wesley
column
index. Maps the Address instance attributes
Pub Date: June 28, 2002
to the column in the table(s) for editing"""

Table of
Contents

ISBN: 0-201-61616-5

Pages: 640

# Get the email, phone and name from the address object.
email, phone = address.email(), address.phoneNumber()
Characterized by ease of use, richness of expression, and concise syntax, Python has
name = address.name()
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
# Set the value based on the column
the two languages, when used in combination, ideal for Web and distributed enterprise
# The columnIndex is the name so set the name
application development.

# in the address object.


# Since
name is
used
for
the
listprogramming.
and keysUsing
in the
This tutorial
beginsthe
with coverage
of some
of the
basics
of Python
#
dictionary,
we
must
change
both
list
item
and
plenty of skill-building exercises and interactive programming sessions, this book willthe
# dictionary
key develop
associated
with ofname.
help those
new to programming
an understanding
concepts and practical
if(columnIndex
==
self.NAME):
techniques. For experienced programmers, the book demonstrates Python's breadth of
address.__init__(value,
phone,with
email)
capabilities
and shows the ways that Python interfaces
Java APIs for professional
self.__changeList(value,
name)
application development.
self.__changeDictKey(value, name)
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web

elif(columnIndex
== self.PHONE):
and Enterprise Applications
with Jython covers important topics such as:
address.__init__(name, value, email)
Fundamental programming
concepts, including statements, expressions,
elif(columnIndex
== self.EMAIL):
interpreters, and compilers
address.__init__(name,
phone, value)
basics,
including
operators,
string formatting,
namespaces,
classes,
errors,
columnIndex maps toPython
a particular
attribute
in the
class instance.
It's compared
against three
constants
and
exceptions
(name,phone, and email) to determine the attribute to set.
Object-oriented programming concepts
__init__ and Its Stupid Methods
File input/output
The__init__ method of the address argument sets the attribute. However, if that attribute is name (i.e.,
columnIndex ==self.name
), several
things have to occur. This part of the code was tricky to write
Python's intrinsic
functions
because the name of the address is a key into the dictionary and is used by the list to sort the keys. That means
parsing,keys
andand
manipulating
that if the name changes, soFormatting,
do the dictionary
list values.strings
The best way I could think of to keep
__init__ from becoming an unruly mess was to break it down into several stupid methods.
Interfacing with the Java APIs and working with Java Streams
The first stupid method, __changeList(), removes the old value from the list and inserts the new value in
Using Python and Java Swing to create GUIs
its place.
Working with
SQL and JDBC(TM)
def __changeList(self,
newValue,
oldValue):
"""Change the old value in the list to the new value.
Python and Java applets
Keeps the JList views in sync with this
list
by firing
an event."""
In addition, thePython
book contains
instructions
for downloading
and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
# samples
Get the
thelearning
oldValue
in the list.
and numerous code
makeindex
this bookof
a useful
experience.

# Use the index to index the list,


and change
theuserlist
the new value.
Whether you are a#sophisticated
computer
new tolocation
programming to
or a serious
#
Notify
the
JList
views
subscribed
to will
this model.
application developer, Python Programming with the Java(TM) Class Libraries
index=self.list.index(oldValue)
give you insight into the power of Python and the know-how to put it to work.
self.list[index]=newValue
self.__fireContentsChanged(self, index, index)

777

Then it notifies the list views (JList instances) of the replacement.

The next stupid method,


__changeDictKey()
, removes
the key/value
pairA in
the dictionary
corresponding
Python
Programming with the
Java Class
Libraries:
Tutorial
for Building
to the name. (Recall Web
that the
name
is the key
into the dictionary
and the value is the address instance with
and
Enterprise
Applications
with Jython
that name.) It's a lot like
__changeList()
in that it manages a collection of model data affected by a name
By Richard
Hightower
change in an address instance.
Publisher: Addison Wesley

def __changeDictKey(self,
newKey, oldKey):
Pub Date: June 28, 2002
"""Change the old key in the dictionary
ISBN: 0-201-61616-5
Table of to the new key."""

Contents

Pages: 640

# Get the address stored at the oldKey location.

Characterized by ease of use, richness of expression, and concise syntax, Python has
# Delete the old key value from the dictionary.
remained a premier programming language for more than a decade, and is used by
# Use the new key to create a new location
novices and professionals alike. In particular, its close relationship to Java(TM) makes
# for the address.
the two languages, when used in combination, ideal for Web and distributed enterprise
address = self.dict[oldKey]
application development.

del self.dict[oldKey]
self.dict[newKey]=address
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
Using the old key (oldKey),__changeDictKey() gets the address at the old location and deletes it.
help those new to programming develop an understanding of concepts and practical
Then it uses the new key ( newKey) to set a new location for the address, which was extracted on the first line.
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
Testing
application development.
Python
Programming with
theaddress
Java(TM)
Libraries:
Tutorial
We're not ready to put
AddressModel
in our
bookClass
application
yet.ABefore
wefor
canBuilding
integrateWeb
a fairly
and
Enterprise
Applications
with
Jython
covers
important
topics
such
as:
large piece of code like this, we have to test it with scaffolding code.
TheAddressModel class has to fit well in the MVC architecture, so we want it to handle multiple views
Fundamental
programming
including
statements,
expressions,
that work with ListModel
and TableModel
. Toconcepts,
test for this
we'll use
JList and
JTable, and we'll
andhold
compilers
throw in JTabbedPaneinterpreters,
because it can
several components, each in its own tab.

Python
including
namespaces, classes, errors,
Here's our scaffolding code.
Read basics,
the comments
to operators,
get an ideastring
of theformatting,
flow.
and exceptions

if __name__ == '__main__':
Object-oriented
programming
concepts
from javax.swing
import
JTable,
JList, JFrame, JTabbedPane, JScrollPane
File input/output

# Create an instance of JFrame, JTabbedPane, AddressModel, JTable,


# and Python's
JList.
Pass
the same instance of AddressModel to the table
intrinsic
functions
# and the list constructor.
frame = JFrame('Test
AddressModel')
Formatting, parsing,
and manipulating strings
pane = JTabbedPane()
model = AddressModel()
Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs
list = JList(model)
table = JTable(model)
Working with SQL and JDBC(TM)

# Add the table and the list to the tabbed pane.


Python and Java applets
pane.addTab('table 1', JScrollPane(table))
pane.addTab('list
1',
JScrollPane(list))
In addition, the book
contains
instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,

# and
Create
another
table
and
list.
numerous
code samples
make this
book
a useful learning experience.
table = JTable(model)
list = Whether
JList(model)
you are a sophisticated computer user new to programming or a serious

application developer, Python Programming with the Java(TM) Class Libraries will

# give
Addyouthe
other
the tabbed
insight
into thetable
power of and
Pythonlist
and theto
know-how
to put it to pane.
work.
# Now we have four views that share the same model.
pane.addTab('table 2', JScrollPane(table))
pane.addTab('list 2', JScrollPane(list))

777

# Python
Add the
pane to
the
Programming
with
the frame.
Java Class Libraries: A Tutorial for Building
# Web
Smack
it, pack
it, andwith
show
it off.
and Enterprise
Applications
Jython
frame.contentPane.add(pane)
By Richard Hightower
frame.pack()
frame.visible=1
Publisher: Addison Wesley
Try these exercises:

Table of
Contents

Pub Date: June 28, 2002


ISBN: 0-201-61616-5
Pages: 640

RunAddressModel.py from the command line (jython AddressModel.py). You should get a
Characterized
by ease of use, richness of expression, and concise syntax, Python has
frame that looks
like Figure 16-5.
remained a premier programming language for more than a decade, and is used by
novices and
professionals
alike.
In particular,
its close relationship
to Java(TM) makes
Figure
16-5. The
Initial
Test AddressModel
Frame
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.

This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
Change "Andy Grove" to someone else, and change his phone number and email address. What happens
to the other views (list1
,list2
, and table2
)?
Fundamental
programming
concepts,
including statements, expressions,

interpreters, and compilers


Use the code for AddressModel to create another column in the table called Cell Phone. Edit the code
for Address and AddressModel
to accommodate
it. formatting, namespaces, classes, errors,
Python basics, including
operators, string
and exceptions

Integrating AddressModel with AddressMain


Object-oriented programming concepts
Now that AddressModel has been defined and tested, let's put it in our address book application. To
File input/output
integrate it with AddressMain, we're going to need methods that will load the form with an address, add and
remove an address from thePython's
model, intrinsic
and savefunctions
an address to disk. Before this functionality was in
AddressMain; now it's in the following methods in AddressModel:
Formatting, parsing, and manipulating strings

getAddressAt()
gets the
address
instance
at a working
given rowwith
index
Interfacing
with
the Java
APIs and
Java Streams
getAddressByName()
gets
address
given GUIs
name
Using Python
andthe
Java
Swingbytoa create
addAddress()
adds anwith
address
theJDBC(TM)
model
Working
SQLtoand
removeAddressByName()
applets
removes an address from the model when given the name of the
Python and Java
address

In addition, the book contains instructions for downloading and installing the Python

writeAddress()
the address
to diskKit (JDK). Terminology, definitions, explanations,
language
andsaves
the Java
Development
and numerous code samples make this book a useful learning experience.
Here's the code for these methods:
Whether you are a sophisticated computer user new to programming or a serious

def getAddressAt(self, rowIndex):


application developer, Python Programming with the Java(TM) Class Libraries will
"""Get an Address by rowIndex"""
give you insight into the power of Python and the know-how to put it to work.
return self.__getAddressAtRow(rowIndex)

777

def getAddressByName(self, name):


"""Get an Address by the name property of the address."""
return self.dict[name]

Python Programming with the Java Class Libraries: A Tutorial for Building

def addAddress(self,
address):
Web and Enterprise
Applications with Jython
"""Add
an Hightower
address to the model, and notify the
By Richard
views of the change."""
Publisher: Addison Wesley

# Add
address
Pub Date:
Junethe
28, 2002

to the dictionary,
#
and
get
the
keys
as the list.
ISBN: 0-201-61616-5
Table of self.dict[address.name()] = address
Pages: 640
Contentsself.list = self.dict.keys()
Characterized by ease of use, richness of expression, and concise syntax, Python has
# aSort
addresses,
andmore
find
index
of by
remained
premierthe
programming
language for
than athe
decade,
and is used
#
the
new
address
in
the
list.
novices and professionals alike. In particular, its close relationship to Java(TM) makes
Then notify
the
list and
views.
the two #languages,
when used in
combination,
ideal table
for Web and
distributed enterprise
application development.

self.list.sort()
index
self.list.index(address.name())
This=tutorial
begins with coverage of some of the basics of Python programming. Using
self.__fireIntervalAdded(index,
plenty of skill-building exercises and interactiveindex)
programming sessions, this book will
self.fireTableDataChanged()
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of

def removeAddressByName(self,
name):
capabilities and shows the ways
that Python interfaces with Java APIs for professional
"""Removes
the
address
from
the model and
application development.
notifies views of change."""
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise
Applications
Jython covers
topics such as:
# Remove
the with
address
fromimportant
the dictionary.

del self.dict[name]
Fundamental
statements, expressions,
# Removeprogramming
the nameconcepts,
from including
the list.
and compilers
index = interpreters,
self.list.index(name)

del self.list[index]
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions

# Notify the table and list views that the data changed.
self.fireTableDataChanged()
Object-oriented programming concepts
self.__fireIntervalRemoved(index, index)
File input/output

def writeAddresses(self):
functions
"""WritePython's
the intrinsic
address
data to the file."""
writeAddresses(self.fname, self.dict)
Formatting, parsing, and manipulating strings
Whenever addresses are added or removed from the model, all table and list viewsthe listenersmust be
Interfacing with the Java
APIs and working with Java Streams, and
notified via the __fireIntervalAdded()
,__fireIntervalRemoved()
__fireTableDataChanged() methods.
Using Python and Java Swing to create GUIs

The AddressModelWorking
Codewith SQL and JDBC(TM)
Python
Java applets
Now that we've covered each
part and
of AddressModel
, we can look at its complete code (from
Two\AddressModel.py).
In addition, the book contains instructions for downloading and installing the Python
from address language
importand*the Java Development Kit (JDK). Terminology, definitions, explanations,
and
numerous
codeAbstractListModel,
samples make this book a useful
learning experience.
from javax.swing
import
ListModel

from javax.swing.table import AbstractTableModel, TableModel


Whether you are aimport
sophisticated
computer user new to programming or a serious
from javax.swing.event
ListDataEvent
application
developer,
Python
Programming
with the Java(TM) Class Libraries will
from java.lang import String
give you insight into the power of Python and the know-how to put it to work.

class AddressModel(AbstractTableModel, ListModel):


"""The AddressModel is both a ListModel and a TableModel."""

777

def __init__(self):

"""Initialize
Address
model.
Python
Programming the
with the
Java Class
Libraries: A Tutorial for Building
Read
dictionary
from
file."""
Web
andthe
Enterprise
Applications
with the
Jython
By Richard Hightower
self.dict = None
self.list
= None
Publisher: Addison
Wesley
Pub Date: June 28, 2002

Table of
Contents

# holds the dictionary of addresses.


# holds the sorted list of names,
# which are keys into the dictionary.

ISBN: 0-201-61616-5

self.listeners
= [] #to hold list of ListModelListeners
Pages: 640
# byRead
addresses
fromand
the
file.
Characterized
ease ofthe
use, richness
of expression,
concise
syntax, Python has
self.fname=".\\addr.dat"
#
holds
the
fileand
name
remained a premier programming language for more than a decade,
is usedthat
by
#
holds
the
addresses
novices and professionals alike. In particular, its close relationship to Java(TM) makes
self.dict
readAddresses(self.fname)
the
two languages,= when
used in combination, ideal for Web and distributed enterprise
application development.
# Store the sorted list of names.

self.list
= with
self.dict.keys()
This
tutorial begins
coverage of some of the basics of Python programming. Using
self.list.sort()
plenty
of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
Define
the
column the
names
and locations
in the
techniques.#For
experienced
programmers,
book demonstrates
Python's breadth
of table.
self.columnNames=['Name',
#',Java
'Email']
capabilities
and shows the ways that Python 'Phone
interfaces with
APIs for professional
self.NAME
= 0 # To hold the location of the name column
application
development.

self.PHONE = 1 # To hold the location of the phone number column


Python
Programming
Class Libraries:
A Tutorial for
Web
self.EMAIL
= with
2 the Java(TM)
# To hold
the location
ofBuilding
the email
column
and Enterprise Applications with Jython covers important topics such as:

def __getAddressAtRow(self, rowIndex):


"""Get the address at the specifed row. (Private method)"""
Fundamental programming concepts, including statements, expressions,
interpreters,
compilers
# Getand
the
row name out of the list.

# Use the name to index the dictionary of addresses.

Python basics, including operators, string formatting, namespaces, classes, errors,


# Get the address associated with this row.
and exceptions

name = self.list[rowIndex]
address
= self.dict[name]
Object-oriented
programming concepts
return address
File input/output

def __getAddressAttributeAtColumn(self, address, columnIndex):


Python's
intrinsic
functions of the address at the
"""Get
the
attribute
specified column index."""
Formatting, parsing, and manipulating strings

value = None # Holds the value we are going to return


Interfacing with the Java APIs and working with Java Streams

# Python
Set and
theJava
value
based
on the column index.
Using
Swing to
create GUIs
if(columnIndex == self.NAME):
value
address.name()
Working
with =
SQL
and JDBC(TM)
elif(columnIndex
== self.PHONE):
Python and Java applets
value = address.phoneNumber()
In addition, the book contains instructions for downloading and installing the Python
language
and the Java Development
Kit (JDK). Terminology, definitions, explanations,
elif(columnIndex
== self.EMAIL):
and numerous
code
samples
make
this
book a useful learning experience.
value = address.email()

return value

Whether you are a sophisticated computer user new to programming or a serious


application developer, PythonnewValue,
Programming with
the Java(TM) Class Libraries will
def __changeList(self,
oldValue):
give
you
insight
into
the
power
of
Python
and
the
know-how
to put
it to new
work. value."""
"""Change the old value in the list to
the

777

# Get the index of the oldValue in the list.


# Use the index to index the list,
# and change the list location to the new value.

# Notify with
thetheworld.
Python Programming
Java Class Libraries: A Tutorial for Building
index=self.list.index(oldValue)
Web
and Enterprise Applications with Jython
self.list[index]=newValue
By
Richard Hightower
self.__fireContentsChanged(index, index)
Publisher: Addison Wesley

def __changeDictKey(self,
newKey, oldKey):
Pub Date: June 28, 2002
"""Change
the
old
key
in the dictionary to the new key."""
ISBN: 0-201-61616-5

Table of
Contents

Pages: 640

# Get the address stored at the oldKey location.


# Delete
therichness
old of
key
valueand
from
the
dictionary.
Characterized
by ease of use,
expression,
concise
syntax,
Python has
#
Use
the
new
key
to
create
a
new
location
remained a premier programming language for more than a decade, and is used by
for the alike.
address.
novices and#professionals
In particular, its close relationship to Java(TM) makes
address
= self.dict[oldKey]
the
two languages,
when used in combination, ideal for Web and distributed enterprise
del self.dict[oldKey]
application
development.
self.dict[newKey]=address
This tutorial begins with coverage of some of the basics of Python programming. Using

def __setAddressAttributeAtColumn(self,
value,
address,
columnIndex):
plenty of skill-building exercises and interactive programming
sessions,
this book will
"""Sets
address develop
attribute
at the
help
those newthe
to programming
an understanding
of concepts and practical
columntheindex."""
techniques.corresponding
For experienced programmers,
book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
Get the email, phone and name from the address object.
application#development.

email, phone = address.email(), address.phoneNumber()


Python
with the Java(TM) Class Libraries: A Tutorial for Building Web
nameProgramming
= address.name()
and Enterprise
Applications
with Jython
coverson
important
such as:
# Set
the value
based
the topics
column.

# The columnIndex is the name so set the name


# in the address object.
Fundamental
programming
concepts,
including
statements,
expressions,
# Since
the name
is used
for
the list
and keys in the
interpreters,
and compilers we must change both list item and the
# dictionary,
# dictionary key associated with name.
Python basics, including operators, string formatting, namespaces, classes, errors,
if(columnIndex
== self.NAME):
and exceptions
address.__init__(value, phone, email)
self.__changeList(value,
name)
Object-oriented
programming concepts
self.__changeDictKey(value, name)
File input/output

elif(columnIndex == self.PHONE):
Python's
intrinsic functions
address.__init__(name,
value, email)
Formatting, parsing, and
strings
elif(columnIndex
==manipulating
self.EMAIL):
address.__init__(name, phone, value)
Interfacing with the Java APIs and working with Java Streams

## The following Using


methods
implement
the
ListModel
interface. ##
Python and
Java Swing to
create
GUIs
def getSize(self):
Working with SQL and JDBC(TM)
"""Returns the length of the items in the list."""
return
Pythonlen(self.list)
and Java applets
In addition, the book containsindex):
instructions for downloading and installing the Python
def getElementAt(self,
language
and the Javathe
Development
Terminology,
""" Returns
value Kit
at (JDK).
index.
""" definitions, explanations,
and
numerous
code
samples
make
this
book
a
useful
learning
experience.
return self.list[index]
Whether you are a sophisticated computer
user new to programming or a serious
def addListDataListener(self,
l):
application
developer,
Python
Programming
with the Java(TM)
"""Add a listener that's notified
when Class
theLibraries
model will
changes."""
give
you
insight
into
the
power
of
Python
and
the
know-how
to
put
it
to
work.
self.listeners.append(l)

777

def removeListDataListener(self, l):


"""Remove a listener."""
self.listeners.remove(l)

Python Programming with the Java Class Libraries: A Tutorial for Building

def __fireContentsChanged(self,
index, index1):
Web and Enterprise Applications with Jython
"""Fire
contents
changed.
Notify viewers
By Richard Hightower
that the list changed."""
event
= Addison
ListDataEvent(self,
ListDataEvent.CONTENTS_CHANGED,
Publisher:
Wesley
index, index1)
Pub Date: June 28, 2002
for ISBN:
listener
in self.listeners:
0-201-61616-5
Table of
listener.contentsChanged(event)
Contents

Pages: 640

def __fireIntervalAdded(self,
index, index1):
Characterized by ease of use, richness of expression, and concise syntax, Python has
"""Fire
interval
added.
Notify viewers that
remained a premier programming language for more than a decade, and is used by
the
items
were
added
to the list."""
novices and professionals alike. In particular, its close relationship to Java(TM) makes
event
=
ListDataEvent(self,
ListDataEvent.INTERVAL_ADDED, index,
the two languages, when used in combination, ideal for Web and distributed enterprise
index1)
application development.
for listener in self.listeners:
listener.intervalAdded(event)
This tutorial begins
with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will

def __fireIntervalRemoved(self,
index, index1):
help those new to programming develop an understanding
of concepts and practical
"""FireForinterval
removed from
the
list. Python's
Notifybreadth
viewers."""
techniques.
experienced programmers,
the book
demonstrates
of
event =and
ListDataEvent(self,
ListDataEvent.INTERVAL_REMOVED,
capabilities
shows the ways that Python interfaces
with Java APIs for professional
index, index1)
application development.
for listener in self.listeners:
listener.intervalRemoved(event)
Python Programming
with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

## The following methods implement the TableModel interface. ##


Fundamental programming concepts, l):
including statements, expressions,
def addTableModelListener(self,
interpreters,
and compilers
"""Add
a listener
that gets notified when the
data model changes. Since all we are doing is
Python basics, including operators, string formatting, namespaces, classes, errors,
calling the super, we don't need this method."""
and exceptions
AbstractTableModel.addTableModelListener(self, l)
Object-oriented programming concepts

def removeTableModelListener(self, l):


"""Remove
a listener. Since all we are doing is calling the
File input/output
super, we don't need this method. It's here for example."""
AbstractTableModel.removeTableModelListener(self,
l)
Python's intrinsic functions
Formatting, parsing, and manipulating
strings
def getColumnClass(self,
columnIndex):
"""Returns the common base Class for the column."""
Interfacing
with the Java APIs and working with Java Streams
return
String
Using Python and Java Swing to create GUIs

def getColumnCount(self):
"""Returns
of columns in the data model."""
Working withthe
SQLnumber
and JDBC(TM)
return len(self.columnNames)
Python and Java applets

def getColumnName(self, columnIndex):


In"""Returns
addition, the book
contains
instructions
downloading
and installing
the Python
the
name
of theforgiven
column
by columnIndex."""
language
the Java Development Kit (JDK). Terminology, definitions, explanations,
returnandself.columnNames[columnIndex]
and numerous code samples make this book a useful learning experience.

def getRowCount(self):
Whether
you are a sophisticated
computer
user newin
to programming
serious
"""Returns
the number
of rows
the tableor amodel."""
application
Python Programming with the Java(TM) Class Libraries will
return developer,
len(self.list)
give you insight into the power of Python and the know-how to put it to work.

def getValueAt(self, rowIndex, columnIndex):


"""Returns the cell value at location specified
by columnIndex and rowIndex."""

777

# Get the
address
object
corresponding
to this
Python Programming
with the
Java Class
Libraries:
A Tutorial for Building
address
= self.__getAddressAtRow(rowIndex)
Web
and Enterprise
Applications with Jython
By Richard Hightower

row.

# Get the address attribute


to this column.
value
=
self.__getAddressAttributeAtColumn(address,
columnIndex)
Pub Date: June 28, 2002
# corresponding
Publisher: Addison
Wesley

Table of
Contents

ISBN: 0-201-61616-5

return
value
Pages: 640

def isCellEditable(self,
rowIndex,
columnIndex):
Characterized by ease of use, richness
of expression,
and concise syntax, Python has
"""Returns
if
the
cell
is
editable
theand
given
remained a premier programming language for more than aat
decade,
is used by
rowIndex
and
columnIndex."""
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
#All cells are editable
application development.

return 1

This tutorial begins with coverage of some of the basics of Python programming. Using
def setValueAt(self,
aValue,
rowIndex,
columnIndex):
plenty of skill-building exercises
and interactive
programming
sessions, this book will
"""Sets
value for
thean understanding
cell at the
givenand practical
help
those newthe
to programming
develop
of concepts
columnIndex
rowIndex."""
techniques.
For experiencedand
programmers,
the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
# Get the address object corresponding to this row.
application development.

address = self.__getAddressAtRow(rowIndex)

Python
Programming with the Java(TM) Class Libraries: A Tutorial foraddress,
Building Web columnIndex)
self.__getAddressAttributeAtColumn(aValue,
and Enterprise
Applications
covers important
topics such
# Notify
thatwith
weJython
changed
this value
soas:other

# views can adjust.


self.fireTableCellUpdated(rowIndex, columnIndex)

Fundamental programming concepts, including statements, expressions,


interpreters, and compilers
def getAddressAt(self,
rowIndex):

"""Get
an Address by rowIndex"""
Python basics, including operators, string formatting, namespaces, classes, errors,
return
self.__getAddressAtRow(rowIndex)
and exceptions
def getAddressByName(self,
Object-oriented programmingname):
concepts
"""Get an Address by the name property of the address."""
return
self.dict[name]
File input/output
Python's intrinsic functions
def addAddress(self,
address):
"""Add an address to the model,
and manipulating
and Formatting,
notify parsing,
the views
of thestrings
change."""
Interfacing with the Java APIs and working with Java Streams

# Add the address to the dictionary,


# and
the to
keys
Using Python
andget
Java Swing
createas
GUIsthe list.
self.dict[address.name()] = address
self.list
= self.dict.keys()
Working with
SQL and JDBC(TM)
# Sort
the addresses, and find the index of
Python and
Java applets
# the new address in the list.
In addition, the#book
contains
instructions
downloading
and installing
the Python
Then
notify
the for
list
and table
views.
language
and the Java Development Kit (JDK). Terminology, definitions, explanations,
self.list.sort()
and
numerous
code samples make this book a useful learning experience.
index
= self.list.index(address.name())

self.__fireIntervalAdded(index, index)

Whether
you are a sophisticated computer user new to programming or a serious
self.fireTableDataChanged()
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Pythonname):
and the know-how to put it to work.
def removeAddressByName(self,

"""Removes the address from the model


and notifies views of change."""

777

# Remove the address from the dictionary.

del self.dict[name]
Python
Programming with the Java Class Libraries: A Tutorial for Building
# Remove
the name
from the list.
Web and Enterprise
Applications
with Jython
index
= self.list.index(name)
By
Richard Hightower
del self.list[index]
Publisher: Addison Wesley

Table of
Contents

# Notify
Pub Date: June
28, 2002 the table and list views that the data changed.
self.fireTableDataChanged()
ISBN: 0-201-61616-5
self.__fireIntervalRemoved(index,
index)
Pages: 640

def writeAddresses(self):
Characterized by ease of use, richness of expression, and concise syntax, Python has
"""Write
theprogramming
address language
data for
to more
thethan
file."""
remained
a premier
a decade, and is used by
writeAddresses(self.fname,
self.dict)
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise

if __name__ ==
'__main__':
application
development.
from javax.swing import JTable, JList, JFrame, JTabbedPane, JScrollPan
from javax.swing.event
import
ListDataListener
This tutorial begins with coverage
of some
of the basics of Python programming. Using
class plenty
listenertest
of skill-building(ListDataListener):
exercises and interactive programming sessions, this book will
intervalAdded(self,
e):
helpdef
those new
to programming develop an understanding
of concepts and practical
print 'Interval
Added:
' + `e`Python's breadth of
techniques. For experienced
programmers, the
book demonstrates
def intervalRemoved(self,
e): with Java APIs for professional
capabilities
and shows the ways that Python interfaces
print
'Interval
Removed:
' + `e`
application development.
def contentsChanged(self, e):
Python Programming
with the
Java(TM) Class
Libraries:'A +
Tutorial
print
'Content
Changed:
`e` for Building Web
and Enterprise Applications with Jython covers important topics such as:

# Create an instance of JFrame, JTabbedPane, AddressModel,


# JTable, and JList.
Fundamental
programming
concepts,
statements, expressions,
# Pass
the same
instance
ofincluding
AddressModel
to the table
interpreters,
and compilers
# and
the list
constructor.
frame = JFrame('Test
AddressModel')
Python basics, including operators, string formatting, namespaces, classes, errors,
pane = JTabbedPane()
and exceptions
model = AddressModel()
model.addListDataListener(listenertest())
Object-oriented programming concepts
list = JList(model)
File input/output
table = JTable(model)
Python's intrinsic functions

# Add the table and the list to the tabbed pane.


Formatting, parsing,
manipulating strings
pane.addTab('table
1',and
JScrollPane(table))
pane.addTab('list 1', JScrollPane(list))
Interfacing with the Java APIs and working with Java Streams

# Create
another
Using Python
and Javatable
Swing toand
createlist.
GUIs
table = JTable(model)
list = JList(model)
Working with SQL and JDBC(TM)
# Add
the
table and list to the tabbed pane.
Python
andother
Java applets
# Now we have four views that share the same model.
In addition, the book contains
instructions for downloading and installing the Python
pane.addTab('table
2', JScrollPane(table))
language and the Java2',
Development
Kit (JDK). Terminology, definitions, explanations,
pane.addTab('list
JScrollPane(list))
and numerous code samples make this book a useful learning experience.

# Add the pane to the frame.

Whether
you are
a sophisticated
user newit
to programming
or a serious
# Smack
it,
pack it,computer
and show
off.
application
developer,
Python
Programming
with
the
Java(TM)
Class
Libraries will
frame.contentPane.add(pane)
give
you
insight
into
the
power
of
Python
and
the
know-how
to
put
it
to
work.
frame.pack()

frame.visible=1

777

addr = Address('aaaaa','aaaaaa','aaaaaa')
model.addAddress(addr)

raw_input('Hit
Enter with
to the
continue')
Python Programming
Java Class Libraries: A Tutorial for Building
model.removeAddressByName(addr.name())
Web and Enterprise Applications with Jython
By Richard Hightower

The actual code for implementing AddressModel is only about 100 lines, but the file is about 280 lines.
Comments, document strings,
and Addison
scaffolding
account for the difference. Although it takes up 28 lines,
Publisher:
Wesley
scaffolding saves a lot of
time in isolating and debugging problems. In a production environment, though, you
Pub Date: June 28, 2002
should put any testing code in its own module.

Table of
Contents

ISBN: 0-201-61616-5

Pages: 640

Changes in AddressMain to Accommodate AddressModel


Characterized by ease of use, richness of expression, and concise syntax, Python has
I had to change AddressMain
to useprogramming
AddressModel
. Infor
themore
code than
that follows
theand
modifications
remained a premier
language
a decade,
is used by are
highlighted in bold: novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
from java.awtapplication
importdevelopment.
BorderLayout, FlowLayout

from AddressModel import AddressModel


...
This tutorial begins with coverage of some of the basics of Python programming. Using
...
plenty of skill-building exercises and interactive programming sessions, this book will
Frame=JFrame;help
List=JList;
Panel=JPanel;
Dialog=JDialog;
Button=JButton
those new to programming
develop an understanding
of concepts and
practical
Menu=JMenu; MenuItem=JMenuItem;
MenuBar=JMenuBar;
PopupMenu=JPopupMenu;
techniques. For experienced programmers,
the book demonstrates
Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional

from AddressFormPane
import AddressForm
application development.
...
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
...
and Enterprise Applications with Jython covers important topics such as:

class AddressMain(Frame):
def __init__(self):
Fundamental programming concepts, including statements, expressions,
# Call the base class constructor.
interpreters, and compilers
Frame.__init__(self, "Main Frame")
Python basics, including operators, string formatting, namespaces, classes, errors,
# Create a list.
and exceptions

self.addresses = List()

Object-oriented programming concepts

# Keep forward-compatible with other containers like JFra


self.container
File input/output = JPanel()
self.container.layout = BorderLayout()
Python's intrinsic functions

# Add the addresses list to the container, on the left si


Formatting, parsing,
and manipulating strings
scrollpane
= JScrollPane(self.addresses)
scrollpane.horizontalScrollBarPolicy =
Interfacing with the Java APIs and working with Java Streams
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS
self.container.add(scrollpane,
Using Python and Java Swing to create GUIs BorderLayout.WEST)
# Create
anJDBC(TM)
instance of AddressModel,
Working
with SQL and
# and set the addresses and self model attributes.
model
= and
AddressModel()
Python
Java applets
self.addresses.model = model
Inself.model
addition, the book
= contains
modelinstructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous
this handler
book a usefulfor
learning
experience.
# code
Setsamples
the make
event
the
addresses.

self.addresses.valueChanged = self.__itemSelected

Whether you are a sophisticated computer user new to programming or a serious


application developer,
Python
Programming
with the Java(TM)
# Create
the
AddressForm
and addClass
itLibraries
to thewilleast.
give
you
insight
into
the
power
of
Python
and
the
know-how
to
put
it
to
work.
self.form = AddressForm()

self.container.add(self.form, BorderLayout.EAST)

777

# Create a tabbed pane, and add the container and table


in their own tabs.

# Add the
instance
toA Tutorial
the contentPane.
Python Programming
withJTabbed
the Java Class
Libraries:
for Building
tabbed_pane
=
JTabbedPane()
Web and Enterprise Applications with Jython
table
= JTable(model)
By
Richard Hightower
tabbed_pane.addTab('Edit Address', self.container)
tabbed_pane.addTab('View
Address Book', JScrollPane(table))
Publisher: Addison Wesley
self.contentPane.add(tabbed_pane,
BorderLayout.CENTER)
Pub Date: June 28, 2002

Table of
Contents

ISBN: 0-201-61616-5

# Set up toolbar and menubar.


self.__init__toolbar()
self.__init__menu()
Characterized
by ease of use, richness of expression, and concise syntax, Python has
Pages: 640

remained a premier programming language for more than a decade, and is used by
self.popup
= None
#to hold
the
popup tomenu
novices
and professionals
alike. In particular,
its close
relationship
Java(TM) makes
self.__init__popup()
the
two languages, when used in combination, ideal for Web and distributed enterprise
self.addresses.mousePressed
= self.__popupEvent
application
development.

self.windowClosing = self.__windowClosing

This tutorial begins with coverage of some of the basics of Python programming. Using
# Set the
default
address
in the
listthisand
plenty of skill-building
exercises
and interactive
programming
sessions,
book form.
will
if those
self.model.getSize()
0:
help
new to programming develop >an understanding
of concepts and practical
self.addresses.setSelectedIndex(0)
techniques. For
experienced programmers, the book demonstrates Python's breadth of
address
self.model.getAddressAt(0)
capabilities and
shows the=ways
that Python interfaces with Java APIs for professional
self.form.set(address)
application development.
Python Programming
the frame
Java(TM)and
Class make
Libraries:
Tutorial for Building Web
# Packwith
the
itA visible.
and
Enterprise Applications with Jython covers important topics such as:
self.pack()

self.setSize(600, 300)
self.visible=1

Fundamental programming concepts, including statements, expressions,


interpreters, and compilers

...
...
Python basics, including operators, string formatting, namespaces, classes, errors,
...
and exceptions
def __addAddress_Clicked(self,event):
dialog
= AddAddressDialog(self)
Object-oriented
programming concepts
if dialog.getState() == AddAddressDialog.OK:
addr = dialog.getAddress()
File input/output
self.model.addAddress(addr)
Python's
intrinsic functions
...
Formatting, parsing, and manipulating strings
def __removeAddress_Clicked(self,event):
index = self.addresses.selectedIndex
Interfacing with the Java APIs and working with Java Streams
key = self.addresses.selectedValue
self.model.removeAddressByName(key)
Using Python and Java Swing to create GUIs

#Get
index
of the item before this one
Working
with the
SQL and
JDBC(TM)
#unless the index of the item we removed is 0.
Python#Then
and Javaselect
applets the index.

if index-1 < 0: index = 0


Inelse:
addition,index
the book=contains
instructions
for downloading and installing the Python
index
-1
language
and the Java Development Kit (JDK). Terminology,
self.addresses.selectedIndex
= index definitions, explanations,
and numerous code samples make this book a useful learning experience.

#Set the form to the current address.

Whether
are a sophisticated computer user new to programming or a serious
key =you
self.addresses.selectedValue
application
developer,
Python Programming with the Java(TM) Class Libraries will
address = self.model.getAddressByName(key)
give
you
insight
into
the
power of Python and the know-how to put it to work.
self.form.set(address)

...
...
if __name__ == "__main__":
mainWindow = AddressMain()

777

Python Programming with the Java Class Libraries: A Tutorial for Building

The modifications aren't


extensive, which is a good thing. An important change is the addition of
Web and Enterprise Applications with Jython
JTabbedPane toBy
include
multiple tabs. Run the code. You should get the frames shown in Figures 16-6 and
Richard Hightower
16-7. Try these exercises:
Publisher: Addison Wesley
June
28, Then
2002 check that the list and table views ( JList and JTable)
Add an address toPub
theDate:
address
book.
ISBN: 0-201-61616-5
were updated.

Table of
Contents

Pages: 640

Remove an address from the list.


Characterized by ease of use, richness of expression, and concise syntax, Python has
Add an optional
Web site
address programming
to the address language
book. (That
make
it so
each entry
an optional
Web
remained
a premier
for is,
more
than
a decade,
andhas
is used
by
page URL.) novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
Figure 16-6.
Address Book Entry Form with JTabbedPane
application
development.

This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
Figure 16-7.programming
Address List
with JTabbedPane
Object-oriented
concepts

File input/output
Python's intrinsic functions
Formatting, parsing, and manipulating strings
Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs
Working with SQL and JDBC(TM)
Python and Java applets
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
If you're feeling pretty sure of yourself, try reimplementing the complete address book application in Java.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
JTree
give you insight into the power of Python and the know-how to put it to work.
Breaking things into hierarchies is natural. Think of your computer's file system, which employs drives,
directories, subdirectories, folders, and files to keep things organized. With JTree we can create hierarchical
organizations for any sort of graphical display.

777

The best way to describe


JTree
is as a cross
between
a list and
an organizational
chart. We're
going to
Python
Programming
with
the Java
Class
Libraries: A Tutorial
for Building
andexample
Enterprise
with Jython
illustrate it first withWeb
a simple
and Applications
then with examples
that increase in complexity (and thus become
By Richard Hightower
more realistic).
Publisher: Addison Wesley
JTree's Constructor
Pub Date: June 28, 2002
0-201-61616-5
There Table
are several
versions ofISBN:
the JTree
constructorone takes a hashtable as a parameter; others use vectors,
of

Pages:
tree models,
tree nodes, and arrays.640
We're going to start off with the hashtable version and add some objects to it.
Contents
Don't be scared. A hashtable is much like a Python built-in dictionary objectin early versions of Jython; you
Characterized by ease of use, richness of expression, and concise syntax, Python has
can use the two interchangeably.
remained a premier programming language for more than a decade, and is used by
Create the hashtable.novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
>>> from java.util
Hashtable
applicationimport
development.

>>> dict = Hashtable()


This tutorial begins with coverage of some of the basics of Python programming. Using
Create some sample plenty
objects.
of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
>>> from address
import
Address
techniques.
For experienced
programmers, the book demonstrates Python's breadth of
>>> rick = Address("Rick
Hightower",
"555-1212",
"r@r.cos")
capabilities and shows
the ways that Python
interfaces with Java
APIs for professional
>>> bob = "Bob
DeAnna"
application development.

>>> Kiley = "Kiley Hightower"

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
Add the sample objects
the dictionary.
andtoEnterprise
Applications with Jython covers important topics such as:

>>> dict['Rick'] = rick


>>> dict['Bob'] =Fundamental
bob
programming concepts, including statements, expressions,
>>> dict['Kiley']interpreters,
= Kiley
and compilers
Now that we have some data
in a form
that
we can pass
to a JTree
constructor,namespaces,
we can create
the actual
tree.
Python
basics,
including
operators,
string formatting,
classes,
errors,
and exceptions
ImportJTree, and create an instance of it, passing the hashtable (dict) as a parameter.
Object-oriented programming concepts

>>> from javax.swing import JTree


>>> tree = JTree(dict)
File input/output
Add the tree to the frame, and
showintrinsic
it.
Python's
functions

>>> from javax.swing


import
Formatting,
parsing,JFrame
and manipulating strings
>>> frame = JFrame("Tree Test")
Interfacing with the Java APIs and working with Java Streams
>>> frame.contentPane.add(tree)
javax.swing.JTree[,0,0,0x0,invalid,...
>>> frame.pack() Using Python and Java Swing to create GUIs
>>> frame.visible=1
Working with SQL and JDBC(TM)

The frame should look like Figure 16-8. Seems more like a list than a tree, does it not? We'll fix this later when
Python and Java applets
we define our own model.

In addition, the book contains instructions for downloading and installing the Python
16-8. A Simple
JTree
Tree
language and theFigure
Java Development
Kit (JDK).
Terminology,
definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

The Tree Model

Python Programming with the Java Class Libraries: A Tutorial for Building

LikeJList and JTable


,JTree
uses JFC's
MVC architecture,
which means that every tree has a model.
Web and
Enterprise
Applications
with Jython
You don't have to specify
a model
because JTree does it for you with DefaultTreeModel, from
By Richard
Hightower
javax.swing.tree.
Publisher: Addison Wesley

>>> tree.model.class
Pub Date: June 28, 2002
<jclass javax.swing.tree.DefaultTreeModel
at 9727>
ISBN: 0-201-61616-5

Table of

640
The tree
model is made up Pages:
of tree nodes.
The TreeNode class implements the TreeNode interface. Get the
Contents
root node, and see what class it is.
Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
>>> root = tree.model.getRoot()
novices and professionals alike. In particular, its close relationship to Java(TM) makes
>>> root.class
the two languages, when used in combination, ideal for Web and distributed enterprise
<jclass javax.swing.tree.DefaultMutableTreeNode...>
application development.
Check that the root implements the TreeNode interface.
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
>>> root.class.interfaces
helpjava.lang.Cloneable
those new to programming develop
understanding of concepts and practical
array([<jclass
at an95880612>,
techniques.
For
experienced
programmers,
the
demonstrates Python's breadth of
<jclass javax.swing.tree.MutableTreeNode book
at -509409883>,
capabilities
and
shows
the
ways
that
Python
interfaces
Java APIs for professional
<jclass java.io.Serializable at 1612121508>], with
java.lang.Class)
application development.
The actual interface implemented is MutableTreeNode, which is the second element in the array. Here's
Python Programming
with the TreeNode
Java(TM) Class
how to see if MutableTreeNode
implements
: Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

>>> root.class.interfaces[1].interfaces
array([<jclass javax.swing.tree.TreeNode at -277936731>], java.lang.Class)
Fundamental programming concepts, including statements, expressions,
interpreters,
and compilers built-in function. As we can see,isinstance()
A faster way to do this is with
the isinstance()
returns a 1 (true) value, so root is indeed an instance of TreeNode .
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
>>> isinstance(root,
TreeNode)

1
Object-oriented programming concepts
A leaf is a node that can have no children. You can check if a node is a leaf like this:
File input/output

>>> tree.model.isLeaf(root)
Python's intrinsic functions
0
parsing, and manipulating strings
The0 (false) value tells theFormatting,
story.
Interfacing
Java
and working
with Java
Streams
Now we'll iterate through the
root nodewith
andthe
print
outAPIs
the string
representation
of the
child nodes (we'll also find
out if they're actually leaves).
Using Python and Java Swing to create GUIs

>>> count = tree.model.getChildCount(root)


with SQL and JDBC(TM)
>>> for index in Working
xrange(0,count):
...
child_node
= tree.model.getChild(root, index)
Python and Java applets
...
print child_node
...
printIn addition,
'isLeaf
' + contains
`tree.model.isLeaf(child_node)`
the book
instructions for downloading and installing the Python
...
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
Kiley
and numerous code samples make this book a useful learning experience.
isLeaf 1
Rick
Whether you are a sophisticated computer user new to programming or a serious
isLeaf 1
application developer, Python Programming with the Java(TM) Class Libraries will
Bob
give you insight into the power of Python and the know-how to put it to work.
isLeaf 1

777

The JTree Model Interface

To create our tree model


we have
to implement
thethe
TreeModel
which
has the for
following
methods:
Python
Programming
with
Java Classinterface,
Libraries:
A Tutorial
Building
Web and Enterprise Applications with Jython
By Richard Hightower

addTreeModelListener(listener) allows JTree to subscribe to tree model events


Publisher: Addison Wesley
removeTreeModelListener(listener)
removes the event listener
Pub Date: June 28, 2002

getChild(parent,index)
returns the child of the parent at a given index
ISBN: 0-201-61616-5

Table of
Contents

Pages: 640

getChildCount(parent) returns the child count of the specified parent node


Characterized by ease of use, richness of expression, and concise syntax, Python has

getIndexOfChild(parent,
child)language
returns
index
of athe
child in
remained a premier programming
forthe
more
than
decade,
andtheis parent
used by

novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application
development.
isLeaf(node)
checks
to see if the node is a leaf

getRoot() returns the root of the tree

This tutorial begins with coverage


of some of
Python programming. Using
ValueForPathChanged(path,
newValue)
the
an basics
abstractofmethod

plenty of skill-building exercises and interactive programming sessions, this book will
help those new toreturn
programming
an understanding of concepts
andoften
practical
getRoot() and getChild()
instances develop
of java.lang.Object
, which are
actual tree
techniques.
For
experienced
programmers,
the
book
demonstrates
Python's
breadth of
nodes.
capabilities and shows the ways that Python interfaces with Java APIs for professional
TreeNode definesapplication
the interface
for the nodes, which is one of the reasons that JTree is so complexit's
development.
like a model within a model. Here are its methods:
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
children() returns an enumeration of children

getAllowsChildren()
programming
returns if the node
allows
child nodes
Fundamental
concepts,
including
statements, expressions,
interpreters, and compilers

getChildAt() gets the child at the specified index


Python basics, including operators, string formatting, namespaces, classes, errors,

getChildCount()
returns the count of children in a specified node
and exceptions
getIndex(node)
returns theprogramming
index of the given
child node
Object-oriented
concepts
getParent()File
returns
the parent of a specified child node
input/output
isLeaf() returns
if a specified
is a leaf
Python's
intrinsicnode
functions
Thechildren() method
requires that
TreeNode
return to itstrings
an instance of
Formatting,
parsing,
and manipulating
java.util.Enumeration, which must implement these methods:
Interfacing with the Java APIs and working with Java Streams

hasMoreElements()
returns
there are
more GUIs
elements in the enumeration
Using Python
and true
JavaifSwing
to create
nextElement()Working
returns
theSQL
next and
element
in the collection
with
JDBC(TM)
A short example will illustrate
howand
treeJava
nodes
can contain other tree nodes. Our tree model contains instances of
Python
applets
javax.swing.tree.TreeNode. It doesn't have to, but it's not a bad idea. We'll define three classes:
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
ListEnumeration
implements the java.util.Enumeration interface
and numerous code samples make this book a useful learning experience.

SimpleNode
implements the javax.swing.tree.TreeNode interface
Whether you are a sophisticated computer user new to programming or a serious
application
developer,
Programming with the Java(TM) Class
Libraries will
SimpleModel
implements
the Python
javax.swing.tree.TreeModel
interface
give you insight into the power of Python and the know-how to put it to work.

ListEnumeration

777

TheListEnumeration class helps develop a simple tree node. In its code, you'll notice that the

children() method
returns
an enumerationmore
precisely,
anLibraries:
instance ofA Tutorial for Building
Python
Programming
with the Java
Class
java.util.Enumeration
whichApplications
provides a standard
way to enumerate over a collection of elements
Web and Enterprise
with Jython
while abstracting theBy
collection
type.
Richard Hightower
Here's the code (from TreeModel1\ListEnumeration.py
):
Publisher: Addison Wesley
Date: June 28, 2002
from java.util Pub
import
Enumeration
ISBN: 0-201-61616-5
Table of
Pages:
640
class
ListEnumeration(Enumeration):
Contents

def __init__(self, the_list):


Characterized
by ease
use, richness of expression, and concise syntax, Python has
self.list
= of
the_list[:]
remained
a
premier
programming
language for more than a decade, and is used by
self.count = len(self.list)
novices
and
professionals
alike.
In
particular, its close relationship to Java(TM) makes
self.index = 0

the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
def hasMoreElements(self):

return self.index < self.count

This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
def nextElement(self):
help those new to programming develop an understanding of concepts and practical
object = self.list[self.index]
techniques. For experienced programmers, the book demonstrates Python's breadth of
self.index = self.index + 1
capabilities and shows the ways that Python interfaces with Java APIs for professional
return object
application development.
Let's break it down interactively. Import ListEnumeration.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications
withListEnumeration
Jython covers important topics such as:
>>> from ListEnumeration
import
Create a list containing three integers.
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
>>> mylist = [1,2,3]
Show that the list has beenPython
created.basics, including operators, string formatting, namespaces, classes, errors,
and exceptions

>>> mylist.__class__
Object-oriented programming
concepts
<jclass org.python.core.PyList
at -992650171>
File input/output
Create a ListEnumeration
object, passing it mylist as an argument to the constructor.
Python's intrinsic functions
>>> enum = ListEnumeration(mylist)
>>> enum.__class__
Formatting, parsing, and manipulating strings
<class ListEnumeration.ListEnumeration at -736797627>
Iterate through the list.

Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs

>>> while(enum.hasMoreElements()):
...
print enum.nextElement()
Working with SQL and JDBC(TM)
...
1
Python and Java applets
2
In addition, the book contains instructions for downloading and installing the Python
3
SimpleNode

language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.

Whether TreeNode
you are a sophisticated
user
programming
or a serious
SimpleNode implements
and can becomputer
used alone
ornew
withtoJTree
. Like other
classes that
application
developer,
Python
Programming
with
the
Java(TM)
Class
Libraries
implementTreeNode , it's sort of a model without events. SimpleNode has a parent node,
a listwill
of child
give
you
insight
into
the
power
of
Python
and
the
know-how
to
put
it
to
work.
nodes (which are of type SimpleNode as well), and a property that determines whether a given node is a leaf.
Its constructor optionally creates leaf nodes and adds them to its node list.

777

Here's the code (from TreeModel1\SimpleNode.py):

from javax.swing.tree
import
TreeNode
Python Programming
with
the Java Class Libraries: A Tutorial for Building
from ListEnumeration
import
ListEnumeration
Web and Enterprise
Applications
with Jython
from java.lang
import
Object
By Richard
Hightower
class SimpleNode
(Object,
TreeNode):
Publisher:
Addison Wesley
def __init__(self,
items=[], parent=None, leaf=0):
Pub Date: June 28,name,
2002
self.__nodes
=
[]
ISBN: 0-201-61616-5

Table of
Contents

Pages: 640

self.__name = name
self.__parent
parent
Characterized
by ease of=use,
richness of expression, and concise syntax, Python has
self.__leaf=leaf
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
for
in when
items:
the
two name
languages,
used in combination, ideal for Web and distributed enterprise
= SampleNode(name, parent=self, leaf=1)
applicationnode
development.

self.__nodes.append(node)

This tutorial begins with coverage of some of the basics of Python programming. Using
def getChildAt(self,
index):
plenty of skill-building exercises
and interactive programming sessions, this book will
"Get
child
at the
given
index" of concepts and practical
help
thosethe
new to
programming
develop
an understanding
return For
self.__nodes[index]
techniques.
experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
def children(self):
application development.

'get children nodes '


Python
Programming
with the Java(TM) Class Libraries: A Tutorial for Building Web
return
ListEnumeration(self.__nodes)
and Enterprise Applications with Jython covers important topics such as:

def getAllowsChildren(self):
'Does this node allow children node?'
Fundamental
programming concepts, including statements, expressions,
return
not self.leaf
interpreters, and compilers

def getChildCount(self):
Python basics, including operators, string formatting, namespaces, classes, errors,
'child
count of this node'
and exceptions
return len (self.__nodes)
Object-oriented programming concepts

def getIndex(self, node):


'getFileindex
of node in nodes list'
input/output
try:
Python's
intrinsicself.__nodes.index(node)
functions
return
except ValueError, e:
Formatting,
parsing,
and manipulating strings
return
None
Interfacing with the Java APIs and working with Java Streams

def getParent(self):
'getUsing
parent
node'
Python and
Java Swing to create GUIs
return self.__parent
Working with SQL and JDBC(TM)

def isLeaf(self):
'is Python
leafand
node'
Java applets
return self.__leaf
In addition, the book contains instructions for downloading and installing the Python
In addition to all of TreeNode
methods,
SimpleNode
implements
its own: definitions, explanations,
language and'sthe
Java Development
Kit (JDK).
Terminology,
and numerous code samples make this book a useful learning experience.

__str__()Whether
displays
as a Pythoncomputer
string user new to programming or a serious
youthe
arenode
a sophisticated
application developer, Python Programming with the Java(TM) Class Libraries will

toString()
you
displays
theinto
node
a Javaofprint
string
give
insight
theaspower
Python
and the know-how to put it to work.
__repr__() displays the node as a string for debugging

777

add() adds a SimpleNode child to the list of nodes

setParent(parent)
sets thewith
parent
of Java
a specified
node
Python Programming
the
Class
Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython

getName()By
Richard
gets theHightower
name of a specified node
setName() sets the name of a specified node
Publisher: Addison Wesley

Pub Date:SimpleNode
June 28, 2002 has to extend java.lang.Object, which defines this
FortoString() to function,
ISBN:
0-201-61616-5
method.
I
hope
all
this
will
take
is
defining __str__ in future Jython releases.
Table of

Contents

Pages: 640

Here's part of the SimpleNode class showing its helper methods:


Characterized by ease of use, richness of expression, and concise syntax, Python has
def __str__(self):
remained a premier programming language for more than a decade, and is used by
'str node'
novices and professionals alike. In particular, its close relationship to Java(TM) makes
returntheself.__name
two languages, when used in combination, ideal for Web and distributed enterprise
application development.

def toString(self):
returnThis
self.__str__()
tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will

def __repr__(self):
help those new to programming develop an understanding of concepts and practical
nodes techniques.
= []
For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
for node
in self.__nodes:
application
development.

nodes.append(str(node))
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
if (self.__parent):

tpl=(self.__name, nodes, self.__parent, self.__leaf)


return 'SampleNode(name=%s,list=%s,parent=%s,leaf=%s)' % tpl
else:

Fundamental programming concepts, including statements, expressions,


interpreters, and compilers

tpl=(self.__name, nodes, self.__leaf)


return
% tpl
Python'SampleNode(name=%s,list=%s,leaf=%s)'
basics, including operators, string formatting, namespaces, classes,
errors,
and exceptions

def add(self, node):


self.__nodes.append(node)
Object-oriented programming concepts
node.setParent(self)
File input/output

def setParent(self, parent):


Python's=intrinsic
functions
self.__parent
parent
def setName(self,Formatting,
name):parsing, and manipulating strings
self.__name=name
Interfacing with the Java APIs and working with Java Streams
def getName(self,Using
name):
Python and Java Swing to create GUIs
return self.__name
Working with SQL and JDBC(TM)
The best way to define SimpleNode is to show it building a tree-like structure of nodes.
Python and Java applets
Create a parent node.
In addition, the book contains instructions for downloading and installing the Python
>>> parent = language
SimpleNode("Dick
& Mary")
and the Java Development
Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Create three child nodes: child1,child2, and child3 with their spouses. Pass a list of offspring to each
node.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
>>> child1 = give
SimpleNode("Rick
& Kiley", ["Whitney"])
you insight into the power of Python and the know-how to put it to work.

>>> child2 = SimpleNode("Martha & Miguel", ["Alex", "Nicholai", "Marcus"])


>>> child3 = SimpleNode("Missy & Adam", ["Mary", "Sarah"])

777

Add the children to the parent node.

>>> parent.add(child1)
Python Programming with the Java Class Libraries: A Tutorial for Building
>>> parent.add(child2)
Web and Enterprise Applications with Jython
>>> parent.add(child3)
By Richard Hightower
Iterate through the children
in the parent
node
showing their names.
Publisher:
Addison
Wesley
Pub Date: June 28, 2002
>>> child = parent.children()
ISBN: 0-201-61616-5
>>> Table
children
= parent.children()
of

Pages:
640
>>> Contents
while(children.hasMoreElements()):
...
print children.nextElement()
Characterized by ease of use, richness of expression, and concise syntax, Python has
...
Rick & Kiley remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
Martha & Miguel
Missy & Adam the two languages, when used in combination, ideal for Web and distributed enterprise

application development.
Here's an easier version of this example, using the for loop statement to handle the enumerators:
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
>>> child = parent.children()
those new to programming develop an understanding of concepts and practical
>>> children help
= parent.children()
techniques.
For experienced programmers, the book demonstrates Python's breadth of
>>> for child in children:
capabilities
...
print child and shows the ways that Python interfaces with Java APIs for professional
application development.
...

Rick & Kiley


Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
Martha & Miguel
Missy & Adam and Enterprise Applications with Jython covers important topics such as:
Now let's make the parent tree node a tree model. Import the GUI components that are needed.
Fundamental programming concepts, including statements, expressions,
interpreters,
and compilers
>>> from javax.swing
import
JTree, JScrollPane, JFrame

including
operators,
stringtoformatting,
namespaces,
Create a JTree instance, Python
passingbasics,
the parent
node as
the argument
the JTree
constructor.classes, errors,
and exceptions

>>> tree = JTree(parent)

Object-oriented programming concepts


Create a frame, and add the JTree instance to it. Pack the frame, and make it visible.
File input/output

>>>
>>>
>>>
>>>

frame = JFrame('SimpleNode test')


Python's intrinsic functions
frame.contentPane.add(JScrollPane(tree))
frame.pack()
Formatting, parsing, and manipulating strings
frame.show()

Interfacing with the Java APIs and working with Java Streams
Your end result should look like Figure 16-9.
Using Python and Java Swing to create GUIs
Figure 16-9. A Family Tree
Working with SQL and JDBC(TM)
Python and Java applets
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower
Publisher: Addison Wesley
Pub Date: June 28, 2002

ISBN: 0-201-61616-5

Table of
Contents

Pages: 640

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to
develop an
understanding
of concepts
and practical
Sharing
a programming
Data Model
among
JTree
Views
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
If the tree node works so well, why do we need a model? I can almost hear you asking this question. For the answer,
application development.
think what will happen if child1, Kiley, has a second child.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web

>>> child1
and Enterprise Applications with Jython covers important topics such as:
SimpleNode(name=Rick & Kiley,list=['Whitney', 'Rick JR.'],parent=Dick &
Mary,leaf=0)
Fundamental programming concepts, including statements, expressions,
To make this clearer, we can
write this:
interpreters,
and compilers

>>> kiley = child1


Python basics, including operators, string formatting, namespaces, classes, errors,
Create the baby node.

and exceptions
Object-oriented programming concepts

>>> baby = SimpleNode("Rick JR.")


>>> kiley.add(baby)
File input/output
Show Kiley's children.

Python's intrinsic functions

>>> children = kiley.children()


Formatting, parsing, and manipulating strings
>>> for child in children:
...
print child
Interfacing with the Java APIs and working with Java Streams
...
Using Python and Java Swing to create GUIs
Whitney
Rick JR.
Working with SQL and JDBC(TM)
If you look at Kiley's children in the JTree node, you'll see that it's out of sync. Worse yet, it will be out of sync with
Python
andwhy
Javawe
applets
any other Jtree you create.
That's
need models. Unlike nodes, they keep the data and the view
synchronized.
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
SampleModel
and numerous code samples make this book a useful learning experience.
you are a sophisticated computer user new
programming
a serious
Deriving your nodesWhether
from javax.swing.tree.TreeNode
isn't to
mandatory
if youordefine
your own
application
developer,
Python
Programming
with the Java(TM)
Class Libraries will
model. The TreeModel
interface
abstracts
a node,
which can therefore
derive from
give you
into the
of Python
and the know-how
to putan
it ID
to work.
java.lang.Object
andinsight
implement
nopower
interfaces
at all. TreeModel
can have
of a database
record as a member, so, instead of reading memory out of a Python list, you can get data out of the database via
the associated tree model.

777

Models keep data and views in sync. The question is how. I'll show you, with a tree model I created called

SampleModel.

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
ImportSampleModel
from the
SampleModel.py module.
By Richard
Hightower

>>> from SampleModel import SampleModel


Publisher: Addison Wesley

Pub Date: June 28,


2002
Create an instance of SampleModel
by passing
its constructor the name of the root node.
ISBN: 0-201-61616-5

Table of

>>> Contents
tree_model = Pages:
SampleModel("Dick
& Mary")
640
Add the two branches
(nodes) of the
therichness
root. The
node has
created.
Characterized
bytree
easeoff
of of
use,
of addNode()
expression, andmethod
concisereturns
syntax,the
Python
remained a premier programming language for more than a decade, and is used by
>>> tree_model.addNode("Martha
["Alex",
"Nicholai",
"Marcus"])
novices and professionals alike.&InMiguel",
particular, its close
relationship
to Java(TM) makes
>>> tree_model.addNode("Missy
&
Adam",
["Mary",
"Sarah"])
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
Create the last branch, and save it. Kiley is a handle we'll use later.

This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help
thoseany
new
to programming
an understanding
concepts
andthe
practical
Notice that we haven't
called
methods
on a node develop
object. Instead,
we've dealtofdirectly
with
model, which
techniques.
For
experienced
programmers,
the
book
demonstrates
Python's
breadth of
encapsulates node manipulation.
capabilities and shows the ways that Python interfaces with Java APIs for professional
application
Now let's create some
views for development.
our model. Import all JFC components that are needed.

>>> Kiley=tree_model.addNode("Rick & Kiley", ["Whitney"])

Python Programming
withJFrame,
the Java(TM)
Class Libraries:
A Tutorial for Building Web
>>> from javax.swing
import
JTree,
JScrollPane
and Enterprise Applications with Jython covers important topics such as:
Create the first view.

>>>
>>>
>>>
>>>
>>>

Fundamental programming
concepts, including statements, expressions,
frame1 = JFrame("View
1-No Scroll")
interpreters, and compilers
tree = JTree(tree_model)
frame1.contentPane.add(tree)
frame1.pack()Python basics, including operators, string formatting, namespaces, classes, errors,
frame1.show()and exceptions

Create the second view.

>>>
>>>
>>>
>>>
>>>

Object-oriented programming concepts

File input/output2-With Scroll")


frame2 = JFrame("View
tree2 = JTree(tree_model)
Python's intrinsic functions
frame2.contentPane.add(JScrollPane(tree2))
frame2.pack()Formatting, parsing, and manipulating strings
frame2.show()

Interfacing with the Java APIs and working with Java Streams
Expand the Rick & Kiley node in both views. Your result should be the two views in Figure 16-10.
Using Python and Java Swing to create GUIs
Figure 16-10. Two SampleModel Views
Working with SQL and JDBC(TM)
Python and Java applets
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Now for the true litmus test. Will both views be changed if the family tree changes; that is, will the views be

synchronized with the


data? As
before, we'll with
say that
hasClass
a second
child, soA we
need tofor
add
a node to
Python
Programming
theKiley
Java
Libraries:
Tutorial
Building
Rick & Kiley.Web and Enterprise Applications with Jython
By Richard Hightower

>>> tree_model.addNode('Rick JR.', parent=Kiley)


Publisher: Addison Wesley

Figure 16-11 shows that the new node was added to both views.
Pub Date: June 28, 2002

Table of
Contents

ISBN: 0-201-61616-5

Figure 16-11. A Blessed Event for Views 1 and 2

Pages: 640

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
Event Notification
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise
Applications
withofJython
covers
topics
suchwhen
as: the model data
Just like the table model,
the tree model
keeps a list
listeners,
all ofimportant
which are
notified
changes. Since TreeModel controls access to the nodes, we can add code to it, in the addNode() method,
to fire a notification event. Here's the addNode() method with its helpers:
Fundamental programming concepts, including statements, expressions,
compilers
def addNode(self,interpreters,
name, and
children=[],
parent=None):

# Set the value of the leaf.


Python basics, including operators, string formatting, namespaces, classes, errors,
# No children means the node is a leaf.
and exceptions
leaf = len(children)==0
# Create
a SampleNode,
Object-oriented
programming concepts
# and add the node to the given parent.
node = SampleNode(name,
children, leaf=leaf)
File input/output
self.__add(node, parent)
Python's intrinsic functions
return node
Formatting,
parsing, and manipulating
addNode() creates an instance
of SampleNode
and passes strings
its constructor the addNode() arguments.
If the children argument is empty, the instance is set as a leaf. addNode() calls the __add() helper
Interfacing
theused
Javaas
APIs
and working
Java
StreamsHere's the code for
method and then returns the
node so itwith
can be
a handle
to other with
model
methods.
__add():
Using Python and Java Swing to create GUIs

def __add(self, node, parent=None):


with SQL and
# IfWorking
the parent
isJDBC(TM)
none,
# then
set
the
parent
to the root.
Python and Java applets
if not parent:
= book
self.getRoot()
Inparent
addition, the
contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
# numerous
Add thecode
node
tomake
thethisparent,
and
samples
book a useful learning experience.

# and notify the world that the node changed.


parent.add(node)
Whether you are a sophisticated computer user new to programming or a serious
self.fireStructureChanged(parent)
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

__add() adds the given node to the given parent. If the parent is None, the root node becomes the default
parent. Adding the node to the parent invokes the fireStructureChanged event, which notifies all

777

listeners (that is, views). Here's the code:

def fireStructureChanged(self,
node):
Python Programming with the
Java Class Libraries: A Tutorial for Building
# Get
the path
to the with
root
node.
Web
and Enterprise
Applications
Jython
#Richard
Create
a TreeModelEvent class instance.
By
Hightower
path = self.getNodePathToRoot(node)
event = Publisher:
TreeModelEvent(self,
path)
Addison Wesley
Pub Date: June 28, 2002

# Notify
every tree model listener that
ISBN: 0-201-61616-5
Table of
# this
tree
model changed at the tree path.
Pages: 640
Contents
for listener in self.listeners:
listener.treeStructureChanged(event)
Characterized
by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by

fireStuctureChanged iterates through the listener list and calls each listener's
novices and professionals alike. In particular, its close relationship to Java(TM) makes
treeStructureChanged() method, passing a TreeModelEvent instance. To create the instance,
the two languages, when used in combination, ideal for Web and distributed enterprise
TreeModelEvent's constructor needs a patha list of nodesfrom the root to the changed node. This is
application development.
how the view notification is carried out and thus how views stay in sync with the data model.

This tutorial begins with coverage of some of the basics of Python programming. Using
Get the path with the getNodePathToRoot() method.
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming
develop an understanding of concepts and practical
def getNodePathToRoot(self,
node):
techniques.
For
experienced
programmers,
the book
demonstrates Python's breadth of
parent = node # Holds the current
node.
capabilities
and
shows
the
ways
that
Python
interfaces
with Java APIs for professional
path=[]
# To hold the path to root.
application development.

# Get the path to the root


Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
while not parent is None:
and Enterprise Applications with Jython covers important topics such as:
# Add the parent to the path, and then get the
# parent's parent.
path.append(parent)
Fundamental programming concepts, including statements, expressions,
parent
= parent.getParent()
interpreters,
and compilers
Python basics,
including operators, string formatting, namespaces, classes, errors,
#Switch
the order
and exceptions
path.reverse()
return path
Object-oriented programming concepts
This event does just what is says it does: it gets the node's path to the root. It should be obvious from the
comments how it works. File input/output
Python's intrinsic functions

Additional Tree Model Methods

Formatting, parsing, and manipulating strings


The rest of the tree model is somewhat boring. Two methods add and remove listeners, and several other
Interfacing
with the
Java
APIs corresponding
and working with
Java Streams instances.
methods delegate responsibility
for specific
tasks
to their
SimpleNode

Using Python and Java Swing to create GUIs


class SampleModel(TreeModel):
def __init__(self, root_name):
with SQL and JDBC(TM)
root Working
= SampleNode(root_name,
[])
self._root = root
Python and Java applets
self.listeners = [] # to hold TreeModel listeners
#methods
implement
the TreeModel
interface.
In addition, theThe
bookfollowing
contains instructions
for downloading
and installing
the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,

def addTreeModelListener(self,
listener):
and numerous code samples make this book
a useful learning experience.
self.listeners.append(listener)

Whether you are a sophisticated computer user new to programming or a serious

def removeTreeModelListener(self,
listener):
application developer, Python Programming with
the Java(TM) Class Libraries will
self.listeners.remove(listener)
give you insight into the power of Python and the know-how to put it to work.
def getChild(self, parent, index):
return parent.getChildAt(index)

777

def getChildCount(self,
parent):
Python Programming with the
Java Class Libraries: A Tutorial for Building
return
parent.getChildCount()
Web and Enterprise
Applications with Jython
By Richard Hightower

def getIndexOfChild(self, parent, child):


return
parent.getIndex(child)
Publisher:
Addison Wesley
Pub Date: June 28, 2002

def getRoot(self):
ISBN: 0-201-61616-5
Table of
return
self._root
Pages: 640
Contents

def isLeaf(self,
node):
Characterized by ease
of use, richness of expression, and concise syntax, Python has
return
node.isLeaf()
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes

def valueForPathChanged(self,
path,
newValue):
the two languages, when used in combination,
ideal
for Web and distributed enterprise
node
= path.getLastPathComponent()
application
development.
node.setName(newValue)
... This tutorial begins with coverage of some of the basics of Python programming. Using
... plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
You can see that most
of the work
done by the programmers,
underlying treethe
nodes
the noninterface
methods.
techniques.
Forisexperienced
bookand
demonstrates
Python's
breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.

DefaultMutableTreeNode
DefaultTreeModel
Python Programming with the Java(TM)and
Class Libraries:
A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
Another way to use JTree is with DefaultMutableTreeNode and
DefaultTreeModel. Once you understand TreeModel, these classes are easy. Look them
Fundamental programming
concepts,
including
statements,
expressions,
up in the Java API documentation.
As an exercise,
use them
to implement
the last
interactive
interpreters, and compilers
session.

Handling JTree

Python basics, including operators, string formatting, namespaces, classes, errors,


and exceptions
Events
Object-oriented programming concepts

JTree publishes the following event properties:


File input/output

treeExpanded a node has expanded; associated with


Python's intrinsic functions
javax.swing.event.TreeExpansionListener and passed an instance of
java.swing.event.TreeExpansionEvent
Formatting, parsing, and manipulating strings
treeCollapsedInterfacing
a node has
associated
with with Java Streams
withcollapsed;
the Java APIs
and working
javax.swing.event.TreeExpansionListener and passed an instance of
javax.swing.event.TreeExpansionEvent
Using Python and Java Swing to create GUIs
treeWillExpand
a node
expand
(used to fetch data, as needed, into the tree model);
Working
withwill
SQL
and JDBC(TM)
associated with javax.swing.event.TreeWillExpandListener and passed an instance
ofjavax.swing.eventTreeExpansionEvent
Python and Java applets
treeWillCollapse
abook
nodecontains
will collapse;
associated
with
In addition, the
instructions
for downloading
and installing the Python
javax.swing.event.TreeWillExpandListener
and passeddefinitions,
an instanceexplanations,
of
language and the Java Development Kit (JDK). Terminology,
javax.swing.event.TreeExpansionEvent
and numerous code samples make this book a useful learning experience.
valueChanged
ayou
newarenode
was selected;
associated
Whether
a sophisticated
computer
userwith
new to programming or a serious
javax.swing.event.TreeSelectionListener
andJava(TM)
passed anClass
instance
of
application developer, Python Programming with the
Libraries
will
javax.swing.event.TreeSelectionEvent
give you insight into the power of Python and the know-how to put it to work.
A little confusing? Let's look at an example that uses the event mechanism to put these properties to work. It's
fromTreeModel1\TreeEvents.py.

777

from SampleModel
SampleModel
Pythonimport
Programming
with the Java Class Libraries: A Tutorial for Building
from javax.swing
import
JFrame,
JTree,
JScrollPane
Web and
Enterprise
Applications
with Jython
def handleTreeExpanded(event):
By Richard Hightower
global g_event
print "Tree
Expanded"
Publisher:
Addison Wesley
showPath(event.path)
Pub Date: June 28, 2002
g_event = event
ISBN: 0-201-61616-5

Table of

Pages: 640

def Contents
handleTreeCollapsed(event):
global Characterized
g_event by ease of use, richness of expression, and concise syntax, Python has
print "Tree
remainedCollapsed"
a premier programming language for more than a decade, and is used by
showPath(event.path)
novices and professionals alike. In particular, its close relationship to Java(TM) makes
g_eventthe=two
event
languages, when used in combination, ideal for Web and distributed enterprise
application development.

def handleTreeWillExpand(event):
global This
g_event
tutorial begins with coverage of some of the basics of Python programming. Using
print "Tree
Expand"
plenty of Will
skill-building
exercises and interactive programming sessions, this book will
showPath(event.path)
help those new to programming develop an understanding of concepts and practical
g_eventtechniques.
= event
For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional

def handleTreeWillCollapse(event):
application development.
global g_event
Python Programming
with the Java(TM) Class Libraries: A Tutorial for Building Web
print "Tree
Will Collapse"
and Enterprise Applications with Jython covers important topics such as:
showPath(event.path)
g_event = event
Fundamental programming concepts, including statements, expressions,
def handleValueChanged(event):
interpreters, and compilers
global g_event
print "Value
Changed"
Python basics, including operators, string formatting, namespaces, classes, errors,
showPath(event.path)
and exceptions
g_event = event
Object-oriented programming concepts

def showPath(treePath):
path = "" File input/output
count = treePath.pathCount
Python's
intrinsic functions
for index in
range(0,count):
node = treePath.getPathComponent(index)
strings + "]"
path Formatting,
= path parsing,
+ "->and
["manipulating
+ str(node)
print path

Interfacing with the Java APIs and working with Java Streams

tree_model = SampleModel("Dick
& Mary")
Using Python and Java Swing
to create GUIs
tree_model.addNode("Martha & Miguel", ["Alex", "Nicholai", "Marcus"])
tree_model.addNode("Missy
& Adam",
["Mary", "Sarah"])
Working with SQL
and JDBC(TM)
Kiley=tree_model.addNode("Rick & Kiley", ["Whitney"])
Python and Java applets

frame = JFrame("Tree Events")


In addition, the book contains instructions for downloading and installing the Python
tree = JTree(tree_model)
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
frame.contentPane.add(tree)
frame.pack() and numerous code samples make this book a useful learning experience.
frame.show()
Whether you are a sophisticated computer user new to programming or a serious
application
developer,
Programming with the Java(TM) Class Libraries will
# A node
in the
tree Python
expanded.
give
you
insight
into
the
power
of Python and the know-how to put it to work.
tree.treeExpanded = handleTreeExpanded

# A node in the tree collapsed.


tree.treeCollapsed = handleTreeCollapsed
# A node in the tree will expand.
tree.treeWillExpand = handleTreeWillExpand

777

# A node
in Programming
the tree will
collapse.
Python
with the
Java Class Libraries: A Tutorial for Building
tree.treeWillCollapse
= handleTreeWillCollapse
Web and Enterprise
Applications with Jython
# A newByRichard
node Hightower
was selected.
tree.valueChanged = handleValueChanged
Publisher: Addison Wesley

Notice that there's an event


handler for every possible event. The handler prints out the path of the event using
Pub Date: June 28, 2002
the tree path associated with it. It also copies the last handler to a global variable, g_event.
Table of
Contents
TreeEvents.py

ISBN: 0-201-61616-5

Pages: 640

Example

Characterized by ease of use, richness of expression, and concise syntax, Python has
Let's do an interactive
session,afirst
typing
this at the system
prompt:
remained
premier
programming
language
for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
Expand the first nodeapplication
to get the development.
following output:

C:\jython_book\scripts\chap16\TreeModel1>jython -i TreeEvents.py

This tutorial begins with coverage of some of the basics of Python programming. Using
Tree Will Expand
plenty of skill-building
and interactive programming sessions, this book will
-> [Dick & Mary]->
[Martha exercises
& Miguel]
help
those
new
to
programming
develop
an understanding of concepts and practical
Tree Expanded
techniques.
For
experienced
programmers,
the book demonstrates Python's breadth of
->[Dick & Mary]-> [Martha & Miguel]
capabilities and shows the ways that Python interfaces with Java APIs for professional
development.
Select the first leaf inapplication
the first node
to get this output:

Value ChangedPython Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise
Applications
with Jython covers
important topics such as:
-> [Dick & Mary]->
[Martha
& Miguel]->
[Alex]
Collapse the first node.

Fundamental programming concepts, including statements, expressions,


interpreters, and compilers
Tree Will Collapse

-> [Dick & Mary]-> [Martha & Miguel]


Tree Collapsed Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
-> [Dick & Mary]->
[Martha & Miguel]
Object-oriented
That was how to get the whole
path, but ourprogramming
only interest concepts
is in the last node. We can get that by inspecting the
last event, which is stored in g_event.
File input/output
The event has a property called path, which is an instance of TreePath .
Python's intrinsic functions

>>> g_event.path.class
Formatting, parsing, and manipulating strings
<jclass javax.swing.tree.TreePath at -1128707474>
Interfacing with the Java APIs and working with Java Streams

TreePath has a method called getLastPathComponent().

Using Python and Java Swing to create GUIs

>>> dir (g_event.path.class)


['getParentPath',Working
'path',
'getPathComponent',
'pathCount',
with SQL
and JDBC(TM)
'pathByAddingChild', 'getPath', 'isDescendant', 'getPathCount',
'lastPathComponent',
'parentPath',
'getLastPathComponent']
Python and
Java applets
getLastPathComponent()
returns
the node
selected. for downloading and installing the Python
In addition, the book
contains
instructions
language and the Java Development Kit (JDK). Terminology, definitions, explanations,

>>> g_event.path.getLastPathComponent()
and numerous code samples make this book a useful learning experience.
SampleNode(name=Martha & Miguel,list=['Alex', 'Nicholai', 'Marcus'],
parent=Dick&
WhetherMary,leaf=0)
you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
That about covers tree
view
make
sure you
try these exercises:
give
youevents.
insightTo
into
the power
of understand
Python and them,
the know-how
to put it to work.

777

Add a JTree component to the address book example that replaces the JList component. Group the
addresses by categorybusiness, personal, and so forth. JTree will show the category and all of its
addresses. Clicking on a particular category should show all of its items in the table. Clicking on a

particular address
should
show that address
in the
entry Class
form. Libraries: A Tutorial for Building
Python
Programming
with the
Java
Web and Enterprise Applications with Jython

Modify the tree


that categories
and subcategories can be added to it.
Byso
Richard
Hightower
Addison Wesley
JToolBar andPublisher:
Actions
Pub Date: June 28, 2002

We'veTable
improved
the addressISBN:
book 0-201-61616-5
application with the addition of JTabbedPane,JTable, and (if you did
of

Pages:
640
the exercises)
ContentsJTree. Still, something's missing.

Characterized
of use,
richness
of expression,
and concise
syntax,
has
In the early days of Java
there was by
no ease
Swing,
and AWT
didn't
have a toolbar.
This meant
that Python
most developers
remained
a
premier
programming
language
for
more
than
a
decade,
and
is
used
by
used panels, which is what I did in the address book application. I had two reasons for this: to show how
novices and professionals
alike. Inwork
particular,
closeintroducing
relationshipactions.
to Java(TM) makes
JPanel and the BorderLayout
layout manager
and toitsavoid
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
Actions
This tutorial begins with coverage of some of the basics of Python programming. Using
We can avoid actionsplenty
no longer.
Any introduction
to JToolBar
has
to include them.
I heldthis
offbook
until will
now
of skill-building
exercises
and interactive
programming
sessions,
because actions are ahelp
higher
abstraction
than
components,
and
I
thought
you
should
have
a
good
grip
on
those new to programming develop an understanding of concepts and practical
components first. techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
Think of an action as a command. An item on a menu that says "remove address" is one example; another is a
application development.
button on a toolbar that says the same thing. The main difference is that an action added to a toolbar usually
becomes a button and
an action
added to a with
menuthe
usually
becomes
item.
Python
Programming
Java(TM)
ClassanLibraries:
A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
The following code, from our third iteration of the address book application in this chapter, uses
javax.swing.JToolBar and javax.swing.AbstractAction to show how actions work.
Notice that the actions created
are used by
both a popup
menu and
a menubar
menu, which
makes the code
Fundamental
programming
concepts,
including
statements,
expressions,
much shorter.
interpreters, and compilers
First we define two classesPython
that extend
AbstractAction
one for
adding and
one for removing
basics,
including operators, :string
formatting,
namespaces,
classes, addresses.
errors,
and exceptions

class Add (AbstractAction):


def __init__(self,
Object-oriented this):
programming concepts
self.this = this
AbstractAction.__init__(self,
"Add")
File input/output
Python's intrinsic functions event):
def actionPerformed(self,
self.this.addAddress_Clicked()

Formatting, parsing, and manipulating strings

class Remove (AbstractAction):


Interfacing with the Java APIs and working with Java Streams
def __init__(self, this):
self.this
= and
this
Using Python
Java Swing to create GUIs
AbstractAction.__init__(self, "Remove")
Working with SQL and JDBC(TM)

def actionPerformed(self, event):


Python and Java applets
self.this.removeAddress_Clicked()
addition,
the book
contains instructions
the Python
As you can see, bothInclasses
extend
AbstractAction
, andfor
thedownloading
only methodand
theyinstalling
have to override
is
language
and Remove
the Java Development
Kit (JDK).
Terminology,
explanations,
actionPerformed()
. The
and Add actions
respectively
delegate definitions,
calls to the AddressMain
and numerous
code samples make
this book a useful learning experience.
classesremoveAddress
and addAddress
.
Whether
a sophisticated
computer
userthey'll
new tobeprogramming
or a serious
Next we instantiate the
actionsyou
andare
add
them to the toolbar.
(Later
added to the menubar
and popup
application developer, Python Programming with the Java(TM) Class Libraries will
menus.)
give you insight into the power of Python and the know-how to put it to work.

#Instantiate the add and remove actions.


addAction = Add(self)
removeAction = Remove(self)

777

# Create
the
toolbar with
panel,
andClass Libraries: A Tutorial for Building
Python
Programming
the Java
# add Web
it and
to Enterprise
the North
borderwith Jython
Applications
# of the
container.
By Richard
Hightower
toolbar = JToolBar()
self.contentPane.add(toolbar,
Publisher: Addison WesleyBorderLayout.NORTH)
Pub Date: June 28, 2002

#Add the actions


to the toolbar.
ISBN: 0-201-61616-5
Table of
toolbar.add(addAction)

Pages: 640
Contents
toolbar.add(removeAction)
Characterized by ease of use, richness of expression, and concise syntax, Python has
This code is much smaller than the code for creating menu items and buttons. Since we're using JToolBar
remained a premier programming language for more than a decade, and is used by
instead of JPanel, we get the additional capability of moving the toolbar at runtime, as illustrated in Figures
novices and professionals alike. In particular, its close relationship to Java(TM) makes
16-12,16-13, and 16-14.
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
Figure 16-12. Main Frame with the Toolbar at the Top
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
Python basics, including operators, string formatting, namespaces, classes, errors,
Figure
16-13. Main Frame with the Toolbar at the Left
and exceptions
Object-oriented programming concepts
File input/output
Python's intrinsic functions
Formatting, parsing, and manipulating strings
Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs
Working with SQL and JDBC(TM)
Python and Java applets
Figure 16-14. Main Frame with a Floating Toolbar
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

Icons

WithAction in general and AbstractAction in particular, we can easily add support for icons. I did it
with the following code:
Publisher: Addison Wesley

Pub Date: June 28, 2002


class Add (AbstractAction):
ISBN: 0-201-61616-5
def __init__(self,
this):
Table of

self.this
Pages: 640= this
Contents
icon = ImageIcon("./images/add.jpg")
Characterized
by ease of use, richness of expression,
and concise
syntax, Python has
AbstractAction.__init__(self,
"Add",
icon)

remained a premier programming language for more than a decade, and is used by
novices and professionals alike. Inevent):
particular, its close relationship to Java(TM) makes
def actionPerformed(self,
the
two
languages,
when
used
in
combination,
ideal for Web and distributed enterprise
self.this.addAddress_Clicked()
application development.

class Remove (AbstractAction):


This tutorial begins with
coverage of some of the basics of Python programming. Using
def __init__(self,
this):
plenty
of
skill-building
exercises
and interactive programming sessions, this book will
self.this = this
help
those
new
to
programming
develop
an understanding of concepts and practical
icon = ImageIcon("./images/remove.jpg")
techniques.
For
experienced
programmers,
the book
demonstrates Python's
AbstractAction.__init__(self,
"Remove",
icon) breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
def actionPerformed(self,
event):

self.this.removeAddress_Clicked()

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and
Enterprise
The result is shown in
Figure
16-15.Applications with Jython covers important topics such as:
Figure 16-15.
Main Frame
Toolbar
withstatements,
Icons expressions,
Fundamental
programming
concepts,
including
interpreters, and compilers

Python basics, including operators, string formatting, namespaces, classes, errors,


and exceptions
Object-oriented programming concepts
File input/output
Python's intrinsic functions
Formatting, parsing, and manipulating strings
Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs
Working with SQL and JDBC(TM)
Try these exercises:

Python and Java applets


Change the paint
programthe
from
the contains
last chapter
to use JToolBar
for both
shape toolbar
and the
In addition,
book
instructions
for downloading
andthe
installing
the Python
color/fill panel.
For
extra
credit,
add
icons
for
the
shape
buttons.
language and the Java Development Kit (JDK). Terminology, definitions, explanations,

and numerous code samples make this book a useful learning experience.
Add mnemonics and tooltips to all of the components in the address book application.

Summary

Whether you are a sophisticated computer user new to programming or a serious


application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

In this chapter, we explored advanced Swing. We showed an example that employed the JFC components
JTable,JTree,JToolBar , and JTabbedPane, and we discussed JTable and JTree.

777

We extended the address book application to use JTable, which led to a discussion of TableModel and

TreeModel. LaterPython
we changed
menus andwith
toolbars
to use actions
instead of buttons
and for
menu
items.
Programming
the Java
Class Libraries:
A Tutorial
Building
Web and Enterprise Applications with Jython

With what you learned


in this and
the last three chapters, you should be able to create your own Swing-based
By Richard
Hightower
applications.
Publisher: Addison Wesley
Pub Date: June 28, 2002 CONTENTS

Table of
Contents

ISBN: 0-201-61616-5
Pages: 640

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
Object-oriented programming concepts
File input/output
Python's intrinsic functions
Formatting, parsing, and manipulating strings
Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs
Working with SQL and JDBC(TM)
Python and Java applets
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
CONTENTS
Web and Enterprise Applications with Jython
By Richard Hightower

Chapter 17. SQL


and JDBC
Publisher: Addison Wesley
Pub Date: June 28, 2002

A Quick and DirtyISBN:


JDBC
Session
0-201-61616-5
Table of
Programming with
JDBC
Pages:
640and SQL
Contents
SQL Data Definition Language
Characterized by
ease of use, richness of expression, and concise syntax, Python has
SQL Data Manipulation
Language
remained a premier programming language for more than a decade, and is used by
Putting It All TogetherAdding Database Support to the Address Book Application
novices and professionals alike. In particular, its close relationship to Java(TM) makes
Summary the two languages, when used in combination, ideal for Web and distributed enterprise

application development.
Terms in This Chapter
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty
of skill-building exercises and interactive
programming
sessions, this book will
ANSI SQL
Java Virtual
Machine
help those new to programming develop an understanding of concepts and practical
techniques.
the book demonstrates Python's breadth of
autoexec.batFor
fileexperienced programmers,JDBC
capabilities and shows the ways that Python interfaces with Java APIs for professional
Class path development.
Main block
application
Database
Primary
key A Tutorial for Building Web
Python
Programming with the Java(TM) Class
Libraries:
and Enterprise Applications with Jython covers important topics such as:
Database-aware dictionary
RDBMS
Data Definition
Language
Fundamental
programming concepts,Referential
including integrity
statements, expressions,
interpreters, and compilers
Data Manipulation Language
Setter m ethod
Python basics, including operators, string formatting, namespaces, classes, errors,
Dirty flag
Structured Query Language
and exceptions
Foreign
key
tryexcept/tryfinally block
Object-oriented
programming concepts
Garbage
Filecollector
input/output

WinZip

One of the advantages of storing


data
in a database
is that other applications can readily access it. Another
Python's
intrinsic
functions
advantage is that the database takes care of indexing files and such, making data access easier and faster.
Formatting, parsing, and manipulating strings
Databases are a huge topic, one that we can barely scratch the surface of. That said, let me tell you what this
chapterwon't cover: data normalization
theory
anyAPIs
otherand
database-specific
topic.
What it will cover is the
Interfacing with
the or
Java
working with Java
Streams
following, which should be enough SQL for you to use JDBC with a database:
Using Python and Java Swing to create GUIs
Basic Structured Query
Language
Working
with (SQL)
SQL and JDBC(TM)
Rudimentary Data Definition
Language
(DDL)
Python and
Java applets
Connecting toIn
a database
Java contains
Databaseinstructions
Connectivity
addition, with
the book
for(JDBC)
downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
Inserting, accessing,
deleting,code
and samples
updatingmake
data with
JDBC
and numerous
this book
a useful learning experience.
To get you up and running
with
API, we'll computer
do a quickuser
interactive
session. Then or
we'll
get into SQL and
Whether
youthe
areJDBC
a sophisticated
new to programming
a serious
DDL and finally addapplication
database support
to
our
address
book
application.
developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

For More Information

AddisonDWesley
A good book on Publisher:
JDBC is JDBC
atabase Access with Java: A Tutorial and Annotated
Pub Date:
June
2002 1997Addison-Wesley). Also good is the free online
Reference (Hamilton,
Cattell,
and28,
Fisher,
documentation at theISBN:
Javasoft
Web site, java.sun.com.
0-201-61616-5

Table of
Contents

Pages: 640

A Quick andCharacterized
Dirty JDBC
by ease Session
of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
novices
professionals
particular,
close Web
relationship
Java(TM)
makes
Naturally I don't know
what and
database
you havealike.
accessInto,
so on thisitsbook's
site I'mtousing
two standards:
the
two
languages,
when
used
in
combination,
ideal
for
Web
and
distributed
enterprise
Microsoft Access and Java InstantDB. The exercises should work with any SQL database, as long as it has
JDBC support. You application
may have todevelopment.
tweak the statements a little, but after this chapter you should feel comfortable
with that.
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty
skill-building
and interactive
programming
this book will
For Microsoft Access
we'reofgoing
to use theexercises
JDBCODBC
bridge, which
integratessessions,
ODBC-compliant
databases
help
those
new
to
programming
develop
an
understanding
of
concepts
and
practical
with Java applications. (ODBC stands for Open Database Connectivity.) Keep in mind that there
are different
Forrange
experienced
programmers,
the book
demonstrates
Python's
breadth
of
levels of compliance.techniques.
These levels
from bridges
to native client
support
to pure Java.
I picked
Access
capabilities
and
shows
the
ways
that
Python
interfaces
with
Java
APIs
for
professional
because it's ODBC compliant and because you're likely to have at least one such database on your computer.
application development.

Setting Up thePython
ODBC
Driver
Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
If you're using Windows and ODBC, follow the instructions below. If you're using a non-Windows OS or a pure
Java JDBC driver, follow its documentation.
Fundamental programming concepts, including statements, expressions,
1. Open the Windows' interpreters,
control panel,
andcompilers
double-click the ODBC icon.
and
2. Select the system DSN tab, and hit the Add button.
Python
basics,
including
operators,you
string
classes,
3. Select Microsoft Access
from
the list,
or any database
wantformatting,
to use (seenamespaces,
Figure 17-1),
and hiterrors,
the Finish
and exceptions
button.
Object-orientedFigure
programming
concepts
17-1. The
Database List
File input/output
Python's intrinsic functions
Formatting, parsing, and manipulating strings
Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs
Working with SQL and JDBC(TM)
Python and Java applets
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.
4. Typedb_dev for the data source (see Figure 17-2).

777

Figure 17-2. Microsoft Access Setup

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower
Publisher: Addison Wesley
Pub Date: June 28, 2002

Table of
Contents

ISBN: 0-201-61616-5
Pages: 640

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
5. Hit the Create button, and create a database as c:\db_dev\db_dev.mdb (see Figure 17-3).
application development.
Figure
17-3.
CreatingClass
a New
Database
Python Programming
with
the Java(TM)
Libraries:
A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

Fundamental programming concepts, including statements, expressions,


interpreters, and compilers
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
Object-oriented programming concepts
File input/output
Python's intrinsic functions
Formatting, parsing, and manipulating strings
Interfacing with the Java APIs and working with Java Streams
If you're using another database that's compliant with ODBC, the steps and the screen shots may vary, but the
ideas are the same. If my instructions
don't
some
Using Python
andwork,
Javaget
Swing
toonline
create help
GUIsfor the database you've chosen. Also, if
you have problems with the system DSN, try creating a user DSN.
Working with SQL and JDBC(TM)

Setting up InstantDB
Python and Java applets
Whatever database you
use, I recommend
installinginstructions
and using InstantDB,
the oneand
I use
for all of
chapter
In addition,
the book contains
for downloading
installing
thethe
Python
examples. It's extremely
easy, and the
it's open
source (that means
free). Terminology,
Here's how to definitions,
set it up: explanations,
language
Java Development
Kit (JDK).
and numerous code samples make this book a useful learning experience.
1. Create a directory on your hard drive, and name it C:\InstantDB.
2. Go to the WebWhether
site and you
navigate
the Resources\InstantDB
are a to
sophisticated
computer userfolder.
new to programming or a serious
3. Unzip the file application
idb.zip into developer,
the new directory
using
WinZip or
an the
equivalent
(getClass
a copy
of WinZip
Python Programming
with
Java(TM)
Libraries
willat the
WinZip Web give
site). you insight into the power of Python and the know-how to put it to work.
4. OpenC:\InstantDB\DOC\index.htm l.
5. On the left side (the left frame), select the Basic link.
6. Select Installation under the Basic link.
7. Follow the installation instructions, which tell you to add the Classes/idb.jar,Classes/idbf.jar, and

777

5.
6.
7.
Classes/idbexmpl.jar
to your classwith
path.the
AnJava
easy way
to do
this, if you're
using Windows,
is to add
Pythonfiles
Programming
Class
Libraries:
A Tutorial
for Building
the following Web
lines to
your
autoexec.bat
file:
and
Enterprise
Applications
with Jython
By Richard Hightower

SET CLASSPATH=%CLASSPATH%;C:\InstantDB\Classes\idb.jar
SET CLASSPATH=%CLASSPATH%;C:\InstantDB\Classes\idbf.jar
Publisher: Addison Wesley
SET CLASSPATH=%CLASSPATH%;C:\InstantDB\Classes\idbexmpl.jar
Pub Date: June 28, 2002
ISBN: 0-201-61616-5
8. Table
Configure
the environment
variable.
of

Pages:
9. Contents
Run the sample application 640
by navigating to C:\InstantDB\Examples> and entering javac
sample.java at the prompt and then java sample. The DOS prompt session may look like this:
Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
C:\InstantDB\Examples>c:\autoexec.bat
novices and professionals alike. In particular,
its close relationship to Java(TM) makes
C:\InstantDB\Examples>javac
sample.java
the
two
languages,
when
used
in
combination,
C:\InstantDB\Examples>java sample ideal for Web and distributed enterprise
application development.
If you're going to use InstantDB for the first interactive session, be sure you have a copy of db_dev.prp in your
begins
withthe
coverage
of some of the basics
of Python
programming.
Using
working directory. IfThis
you tutorial
don't, copy
it from
scripts\chap17\InstantDB
folder
into the
working directory.
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
Programming
with For
JDBC
andprogrammers,
SQL the book demonstrates Python's breadth of
techniques.
experienced
capabilities and shows the ways that Python interfaces with Java APIs for professional
To start things off, we're
going todevelopment.
create a table, insert some values, and query them.
application

Import the DriverManager


and Class
to load the
JDBC
driver. A Tutorial for Building Web
Python Programming
withclasses
the Java(TM)
Class
Libraries:
and Enterprise Applications with Jython covers important topics such as:

>>> from java.sql import DriverManager


>>> from java.lang import Class

Fundamental programming concepts, including statements, expressions,


Load the driver using Class.forName
which dynamically loads a class into the Java Virtual Machine
interpreters, and ,compilers
(JVM). (See the Java API documentation for more details.) For Microsoft Access via ODBC (or any ODBC
Python basics, including operators, string formatting, namespaces, classes, errors,
database):
and exceptions

>>> Class.forName("sun.jdbc.odbc.JdbcOdbcDriver")
Object-oriented programming concepts
<jclass sun.jdbc.odbc.JdbcOdbcDriver
at -416861389>
For InstantDB:

File input/output

Python's intrinsic functions


>>> Class.forName("jdbc.idbDriver")
<jclass jdbc.idbDriver at -282805662>
Formatting, parsing, and manipulating strings
Just as an HTML page has an HTTP URL, so a database has a JDBC URL. The last part of the URL for
Interfacing
withthat
thewe
Java
and the
working
with
Streams
JdbcOdbcDriver refers
to the DSN
setAPIs
up with
ODBC
dataJava
source
administrator in the last
section. Enter this:
Using Python and Java Swing to create GUIs

>>> url = "jdbc:odbc:db_dev"

Working with SQL and JDBC(TM)

The last part of the URL for InstantDB refers to the database properties file. Enter this:
Python and Java applets

>>> url = "jdbc:idb=db_dev.prp"

In addition, the book contains instructions for downloading and installing the Python
the Java Development
Kit (JDK). Terminology,
definitions,
Now we can pass thelanguage
URL to and
DriverManager
'sgetConnection()
method
and passexplanations,
the user name
and
numerous
code
samples
make
this
book
a
useful
learning
experience.
and password (both of which are blank, i.e., " "). Once we have a connection, we can create a table. Ours will
have two columns, Name and Age, and we'll call it PERSON.
Whether you are a sophisticated computer user new to programming or a serious
application
developer, Python Programming with the Java(TM) Class Libraries will
Create the JDBC connection
object.
give you insight into the power of Python and the know-how to put it to work.

>>> connection = DriverManager.getConnection(url, "","")

777

Create the JDBC statement object.

>>> statementPython
= connection.createStatement()
Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython

Create an SQL DDLBy


statement
that defines a database table.
Richard Hightower

>>> create_table = """CREATE TABLE PERSON (name VARCHAR(50), age INT)"""


Publisher: Addison Wesley

Date: June 28, 2002


Execute the SQL DDL Pub
statement.
ISBN: 0-201-61616-5

Table of

>>> Contents
statement.executeUpdate(create_table)
Pages: 640
-1
Characterized by ease of use, richness of expression, and concise syntax, Python has
Close the connection.
(Leave ita open
if you're
going onlanguage
to the next
remained
premier
programming
forsection.)
more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
>>> connection.close()
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
Go to the database tools, and see that the table was created. The Microsoft Access version is shown in Figure 174. (For the InstantDBThis
version,
usebegins
SQLBuilder,
which of
comes
directory.) Using
tutorial
with coverage
someinofthetheInstantDB
basics of examples
Python programming.
plenty of skill-building exercises and interactive programming sessions, this book will
17-4.
The PERSON
TableMS
Access Version
helpFigure
those new
to programming
develop
an understanding
of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
Object-oriented programming concepts
File input/output
Python's intrinsic functions
Formatting, parsing, and manipulating strings
Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs
Working with SQL and JDBC(TM)

Inserting Data

Python and Java applets

In addition, the book contains instructions for downloading and installing the Python
Now we can start adding
data and
to our
you've disconnected
or restarted
your definitions,
JPython interactive
session,
language
thetable.
Java If
Development
Kit (JDK).
Terminology,
explanations,
you'll have to reconnect
and first.
numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

Reconnecting Your JPython Session

Publisher: Addison
Wesley
ImportDriverManager
and Class
.
Pub Date: June 28, 2002

>>> from java.sql


import DriverManager
ISBN: 0-201-61616-5
Table
>>> offrom java.lang
Pages: 640import Class
Contents

For ODBC: Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
>>> Class.forName('sun.jdbc.odbc.JdbcOdbcDriver')
novices and professionals alike. In particular, its...>
close relationship to Java(TM) makes
<jclass sun.jdbc.odbc.JdbcOdbcDriver
the
two
languages,
when
used
in
combination,
ideal
for Web and distributed enterprise
>>> url="jdbc:odbc:db_dev"
application development.
For InstantDB:
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
>>> Class.forName("jdbc.idbDriver")
help those new to programming
develop an understanding of concepts and practical
<jclass jdbc.idbDriver
at -282805662>
techniques.
For
experienced
programmers,
the book demonstrates Python's breadth of
>>> url = "jdbc:idb=db_dev.prp"
capabilities and shows the ways that Python interfaces with Java APIs for professional
application
development.
Get the connection,
and create
the statement.

Python Programming with the Java(TM) Class Libraries: A Tutorial


Building Web
>>> connection=DriverManager.getConnection(url,
"",for"")
and Enterprise
Applications with Jython covers important topics such as:
>>> statement
= connection.createStatement()
Once you have a JDBC statement
object,programming
you have to create
an insert
stringexpressions,
in order to insert data.
Fundamental
concepts,
includingformat
statements,
(Notice the single quotes around
%s
.
They're
important
for
proper
SQL
syntax.)
interpreters, and compilers

>>> insert = "insert


into including
Personoperators,
(name,
age)
values
('%s',
%d)"
Python basics,
string
formatting,
namespaces,
classes,
errors,
and exceptions
Pass a tuple containing name and age to the string format.
Object-oriented programming concepts

>>> insert % ("Whitney", 3)


"insert into Person
(name, age) values ('Whitney', 3)"
File input/output
Add Whitney to the database.
Python's intrinsic functions

>>> statement.executeUpdate(insert
% ("Whitney",
3))
Formatting, parsing, and manipulating
strings
1
Interfacing with the Java APIs and working with Java Streams

Add Kiley.

Using Python and Java Swing to create GUIs

>>> statement.executeUpdate(insert % ("Kiley", 23))


1
Working with SQL and JDBC(TM)
Add Scott and Nick.

Python and Java applets

>>> statement.executeUpdate(insert
% ("Scott",
34))
In addition, the book contains instructions
for downloading
and installing the Python
1
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.

>>> statement.executeUpdate(insert % ("Nick", 3))


1
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
Add Mary and Adam.
give you insight into the power of Python and the know-how to put it to work.

>>> statement.executeUpdate(insert % ("Mary", 2))


1

777

>>> statement.executeUpdate(insert
% ("Adam",
23))
Python Programming with the Java
Class Libraries:
A Tutorial for Building
1
Web and Enterprise Applications with Jython
By Richard Hightower

Notice that after each addition the executeUpdate() method returns the number of rows affected.
Publisher: Addison Wesley

Go to your database management tools, and view PERSON. Figure 17-5 shows its Microsoft Access version;
Pub Date: June 28, 2002
use SQLBuilder to see the InstantDB version.

ISBN: 0-201-61616-5

Table of
Contents

Pages: 640

Figure 17-5. The PERSON Table with Data Added

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
Object-oriented programming concepts
By the way, keep your connection open. If you've already closed it, see the sidebar on reconnecting.
File input/output

Accessing Data
Python's intrinsic functions
To access the names and ages in our table we query the results object (an instance of
Formatting,
parsing,
and manipulating
java.sql.ResultSet
), which uses
the following
methods:strings

Interfacing with the Java APIs and working with Java Streams
next() iterates through the table; returns 1 if there are more rows
Using Python and Java Swing to create GUIs
getString() gets the name specified in the name string passed to it
Working with SQL and JDBC(TM)
getInt() gets the age specified in the age string passed to it
Python and Java applets

>>> results = statement.executeQuery("select name, age from Person")


In addition, the book contains instructions for downloading and installing the Python
languagework
and the
Java Development Kit (JDK). Terminology, definitions, explanations,
Let's see how these methods
interactively.
and numerous code samples make this book a useful learning experience.
Move to the first row.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
>>> results.next()
give you insight into the power of Python and the know-how to put it to work.
1
Get the name.

777

>>> results.getString("name")

'Whitney'
Get the age.

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

>>> print results.getInt("age")


Publisher: Addison Wesley
3
Pub Date: June 28, 2002

ISBN:
DefineTable
a function
that can be
used0-201-61616-5
repeatedly to get the rest of the results.
of

Contents

Pages: 640

>>> def showResults(results):


...
while(results.next()):
Characterized by ease of use, richness of expression, and concise syntax, Python has
...
name
= results.getString("name")
remained
a premier
programming language for more than a decade, and is used by
...
age
= results.getInt("age")
novices
and professionals
alike. In particular, its close relationship to Java(TM) makes
...
print
name
" in
iscombination,
" + `age`
years
old." enterprise
the two
languages,
when+used
ideal +
for"Web
and distributed
...
application development.
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
>>> showResults(results)
help those new to programming develop an understanding of concepts and practical
Kiley is 23 years
old.
techniques.
For experienced programmers, the book demonstrates Python's breadth of
Scott is 34 years
old.
capabilities
and shows the ways that Python interfaces with Java APIs for professional
Nick is 3 years
old.
application development.
Print the results.

Mary is 2 years old.


Adam is 23 years
old.
Python Programming
with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
Here's how we filter our results to get, say, only persons under the age of four:

>>> select = "select


name,
age from
Person
where
age expressions,
< 4"
Fundamental
programming
concepts,
including
statements,
>>> showResults(statement.executeQuery(select))
interpreters, and compilers
Whitney is 3 years old.
Python basics, including operators, string formatting, namespaces, classes, errors,
Nick is 3 years old.
and exceptions
Mary is 2 years old.
Object-oriented programming concepts
or persons over the age of twenty:
File input/output
>>> select = "select
name, age from Person where age > 20"
>>> showResults(statement.executeQuery(select))
Kiley is 23 yearsPython's
old.intrinsic functions
Scott is 34 years old.
Formatting, parsing, and manipulating strings
Adam is 23 years old.
Interfacing with the Java APIs and working with Java Streams
Functions like count(),sum(), and stdev() allow us to get aggregate data, such as the count of persons
in the table.
Using Python and Java Swing to create GUIs

>>> results = statement.executeQuery("select


count(name) as total from Person
Working with SQL and JDBC(TM)
>>> results.next()
1
Python and Java applets
>>> print results.getString("total")
In addition, the book contains instructions for downloading and installing the Python
6
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
See if you can figureand
outnumerous
what the next
interactive
doing.learning
(They won't
work with InstantDB as
codetwo
samples
make sessions
this bookare
a useful
experience.
of v.3.12.)
Whether you are a sophisticated computer user new to programming or a serious
>>> r = statement.executeQuery("select
asClass
stLibraries
from Person")
application developer, Python Programmingstdev(age)
with the Java(TM)
will
>>> r.next() give you insight into the power of Python and the know-how to put it to work.

1
>>> print "Standard deviation" + r.getString("st")
Standard deviation=13.7501515143167
>>> r = statement.executeQuery("select sum(age) as [sum] from Person")

777

>>> r.next() Python Programming with the Java Class Libraries: A Tutorial for Building
1
Web and Enterprise Applications with Jython
>>> print "Sum
of ages
" + r.getString("sum")
By Richard
Hightower
Sum of ages 88.
Publisher: Addison Wesley
Pub Date: June
28, 2002
Removing and Changing
Data
ISBN: 0-201-61616-5
Table of

Pages:
640 the JdbcTour.py
The first
thing you want to do is import
Contents

module from the InstantDB and Access directories so


you can use its showResults() function in the next interactive sessions. (If you disconnected, refer to the
Characterized by ease of use, richness of expression, and concise syntax, Python has
sidebar on reconnecting.)
remained a premier programming language for more than a decade, and is used by
Let's remove everyone
over twenty.
(Leave outalike.
the asterisk
(*) in the
method
argumentstoifJava(TM)
you're using
novices
and professionals
In particular,
its close
relationship
makes
InstantDB.)
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.

>>> statement.executeUpdate("delete * from Person where age > 20")


3
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
TheexecuteUpdate()
method
3, whichdevelop
means an
thatunderstanding
three records of
were
deleted.
help those
new toreturns
programming
concepts
and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
Now let's do some modifying.
thisshows
next session
we'll
Whitney's
current
then
it. In other
capabilitiesInand
the ways
thatshow
Python
interfaces
with age
Javaand
APIs
forchange
professional
words, we'll update her
record.
Show
Whitney's
current
age.
application development.

>>> select = Python


"select
name, age from Person where name = 'Whitney'"
Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
>>> results =andstatement.executeQuery(select)
Enterprise Applications with Jython covers important topics such as:
>>> showResults(results)
Whitney is 3 years old.
Change it to four.

Fundamental programming concepts, including statements, expressions,


interpreters, and compilers

>>> statement.executeUpdate("update
Person
set age
= 4 where
Python basics, including operators,
string formatting,
namespaces,
classes,name
errors, = 'Whitney'
1
and exceptions
Show Whitney's new age. Object-oriented programming concepts

>>> results = statement.executeQuery(select)


File input/output
>>> showResults(results)
Whitney is 4 years
old.
Python's
intrinsic functions
Formatting, parsing, and manipulating strings

SQL Subsets in InstantDB versus Microsoft Access


Interfacing with the Java APIs and working with Java Streams

InstantDB is a lightweight
database
that
supports
a subset
of the SQL syntax. Microsoft
Using Python
and
Java
Swingonly
to create
GUIs
Access supports only a subset as well, but a larger one. The real problem is that the two databases
don't always supportWorking
the samewith
subset.
SQL and JDBC(TM)

Python and Java applets

SQL Data Definition Language


In addition, the book contains instructions for downloading and installing the Python
language
and(DDL)
the Java
Kit (JDK).
Terminology,
SQL's Data Definition
Language
is Development
for working with
tables and
indexes. A definitions,
table definesexplanations,
a set of columns
and
numerous
code
samples
make
this
book
a
useful
learning
experience.
for different fields of data and is similar to a class in Python. Columns are like class properties or variables; rows
are like class instances.
Whether you are a sophisticated computer user new to programming or a serious
application
Python
Programming
withsections.
the Java(TM) Class Libraries will
DDL has five statements,
whichdeveloper,
we'll look at
in turn
in the following
give you insight into the power of Python and the know-how to put it to work.

Create Table

777

TheCREATE TABLE statement defines the table. It has the following form:

CREATE TABLE Python


tableProgramming with the Java Class Libraries: A Tutorial for Building
(field_name sql_type
[(size)]
[NOT with
NULL]
[index1] , ...)
Web and Enterprise
Applications
Jython
By Richard Hightower

where
Publisher: Addison Wesley
Pub Date: June 28, 2002
field_name is
the name of the field being defined

Table of
sql_type
Contents

ISBN: 0-201-61616-5
Pages:
is a valid
SQL640
type

size is the size


of the fieldby ease of use, richness of expression, and concise syntax, Python has
Characterized
remained a premier programming language for more than a decade, and is used by

NOT NULL specifies


thatprofessionals
the column can't
or equal
to None
novices and
alike.beInempty
particular,
its close
relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
The brackets in the statement
denote
optional parameters.
application
development.
Here's how to createThis
a table
named
Employee:
tutorial
begins
with coverage of some of the basics of Python programming. Using

of skill-building
exercises and interactive programming sessions, this book will
CREATE TABLE plenty
Employee
(
help
those
new
to
programming
develop an understanding of concepts and practical
EmpID
INT
NOT NULL,
techniques.
For
experienced
programmers,
the book demonstrates Python's breadth of
Name
CHAR(20),
capabilities
and
shows
the
ways
that
Python
interfaces with Java APIs for professional
DeptID
INT
NOT NULL,
application development.

CHAR denotes a character, so CHAR(20) denotes a 20-character field.

Create Index

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

Fundamental
statements,
expressions,
Indexing a table speeds data
access. Youprogramming
create a tableconcepts,
index withincluding
the CREATE
INDEX
statement, which has
interpreters, and compilers
the form
Python basics, including operators, string formatting, namespaces, classes, errors,
CREATE INDEX index
exceptions
ON table (field, and
field,
...)
programming
concepts
This is how to add an indexObject-oriented
to our Employee
table:
File input/output
CREATE INDEX SalaryIndex
ON Employee (Salary)

Alter Table

Python's intrinsic functions

Formatting, parsing, and manipulating strings


You modify a table with the ALTER TABLE statement, which has the form
Interfacing with the Java APIs and working with Java Streams

ALTER TABLE table


Python and Java[NOT
Swing to
create GUIs
ADD COLUMN field Using
type[(size)]
NULL]
with table,
SQL and
JDBC(TM)
To add an extra column to Working
the Employee
do this:

ALTER TABLE
ADD COLUMN

Python and Java applets


Employee
Phone CHAR(20)

NOT NULL

In addition, the book contains instructions for downloading and installing the Python
and the Java Development Kit (JDK). Terminology, definitions, explanations,
To drop a column dolanguage
this:
and numerous code samples make this book a useful learning experience.

ALTER TABLE table


Whether you are a sophisticated computer user new to programming or a serious
DROP COLUMN field
application developer, Python Programming with the Java(TM) Class Libraries will
To drop a field in thegive
column
just added
you insight
intodo
thethis:
power of Python and the know-how to put it to work.

ALTER TABLE table


DROP COLUMN field

777

Constraint

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard
Hightower
With the CONSTRAINT
clause
you can mark the EmpID column as the primary key. A primary key is a

unique identifier that indexes the table and defines inter-table relationships. CONSTRAINT has the form
Publisher: Addison Wesley

CREATE TABLE Employee


( 28, 2002
Pub Date: June
EmpID
INT
NOT NULL,
ISBN: 0-201-61616-5
Table Name
of
CHAR(20),

Pages: 640
Contents
DeptID
INT
NOT NULL,
SalaryCharacterized
INT,
by ease of use, richness of expression, and concise syntax, Python has
CONSTRAINT
(EmpID)
remainedEMP_PK_KEY
a premier programming PRIMARY
language for KEY
more than
a decade, and is used by
)
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
Here's another, probably
more common,
way to define a primary key (the only method supported by InstantDB
application
development.
v.3.12):
This tutorial begins with coverage of some of the basics of Python programming. Using
CREATE TABLE plenty
Employee
(
of skill-building
exercises and interactive programming sessions, this book will
EmpID help those new
INTto programming
PRIMARY
KEY,an understanding of concepts and practical
develop
Name techniques.CHAR(20),
For experienced programmers, the book demonstrates Python's breadth of
DeptIDcapabilitiesINT
NULL,
and showsNOT
the ways
that Python interfaces with Java APIs for professional
SalaryapplicationINT,
development.

Phone CHAR(20)

NOT NULL

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
To create a table that's linked to another table, you create a foreign key (the reference to another table) in one to
point to a primary key in the other. As an example, we'll define a foreign key in the Employee table to point to
Fundamental
programming concepts, including statements, expressions,
the primary key in a table called
Department.
interpreters, and compilers
Define the Department table.
Python basics, including operators, string formatting, namespaces, classes, errors,
CREATE TABLE Department
(
and exceptions

DeptID
INT
NOT NULL,
Name
CHAR(20),
Object-oriented
programming concepts
CONSTRAINT DEPT_PK_KEY PRIMARY KEY (DeptID)
)

File input/output

intrinsic
Create the Employee table Python's
with a foreign
keyfunctions
constraint that refers to the Department table's DeptID.
Formatting,
CREATE TABLE Employee
( parsing, and manipulating strings
EmpID
INT
NOT NULL,
Interfacing
with the Java APIs and working with Java Streams
Name
CHAR(20),
DeptID
INT
NOT NULL,
Using Python and Java Swing to create GUIs
Salary
INT,
CONSTRAINTWorking
EMP_PK_KEY
PRIMARY KEY (EmpID),
with SQL and JDBC(TM)
CONSTRAINT DEPT_FK_KEY FOREIGN KEY (DeptID)
REFERENCES
Department (DeptID)
Python
and Java applets
)
In addition, the book contains instructions for downloading and installing the Python
The relationship created
by theand
linking
shows
that each employee
must
be in a department.
language
the Java
Development
Kit (JDK).
Terminology,
definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious

No Foreign
Keys
orPython
Referential
Integrity
InstantDB
application
developer,
Programming with
the Java(TM)in
Class
Libraries will
give you insight into the power of Python and the know-how to put it to work.
InstantDB doesn't support foreign keys or referential integrity. Microsoft Access does support these
concepts, as do most SQL databases you're likely to run into.

777

Drop

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
Richard
Hightower
TheDROP statementBy
has
the form

DROP table_namePublisher: Addison Wesley


DROP index on table
Pub Date: June 28, 2002
ISBN: 0-201-61616-5

Table of
Here's
the Employee
table, that is, delete it from the database:
how to use it to dropPages:
640
Contents

DROP Employee

Characterized by ease of use, richness of expression, and concise syntax, Python has
a premier
programming language for more than a decade, and is used by
Obviously, the use ofremained
DROP requires
caution.
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
Putting It All Together
application development.
Let's show DDL in action
by running
thewith
Access/ddl.py
module,
defines
DDL
statement strings
This tutorial
begins
coverage of
some ofwhich
the basics
of four
Python
programming.
Usingand
then executes each one
withofthe
JDBC statement
object's
plenty
skill-building
exercises
and executeUpdate()
interactive programming method.
sessions, this book will
help those new to programming develop an understanding of concepts and practical
from java.sqltechniques.
importForDriverManager
experienced programmers, the book demonstrates Python's breadth of
from java.lang
import
capabilities
and Class
shows the ways that Python interfaces with Java APIs for professional
application development.

Class.forName('sun.jdbc.odbc.JdbcOdbcDriver')
url="jdbc:odbc:db_dev"
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
connection=DriverManager.getConnection(url,
"", topics
"") such as:
and Enterprise Applications with Jython covers important
statement = connection.createStatement()

create_departmentFundamental
= """ programming concepts, including statements, expressions,
interpreters,
and compilers
CREATE TABLE
Department
(
DeptID
INT
NOT NULL,
including operators, string formatting, namespaces, classes, errors,
Name Python basics,
CHAR(20),
and
exceptions
CONSTRAINT DEPT_PK_KEY PRIMARY KEY (DeptID)
)
Object-oriented programming concepts
"""
create_employee =File"""
input/output
CREATE TABLE Employee (
EmpIDPython's intrinsic
INTfunctions
NOT NULL,
Name
CHAR(20),
Formatting, parsing,
manipulating
DeptID
INT and
NOT
NULL, strings
Salary
INT,
Interfacing EMP_PK_KEY
with the Java APIs and
working with
Streams
CONSTRAINT
PRIMARY
KEYJava
(EmpID),
CONSTRAINT DEPT_FK_KEY FOREIGN KEY (DeptID)
Using Python and Java Swing to create GUIs
REFERENCES Department (DeptID)
)
Working with SQL and JDBC(TM)
"""
Python and Java applets

alter_table = """
ALTER TABLE
Employee
In addition, the book
contains instructions for downloading and installing the Python
ADD COLUMN
CHAR(20)
NULL definitions, explanations,
language Phone
and the Java Development
Kit (JDK).NOT
Terminology,
"""
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
add_index = """
developer, Python Programming
with the
Java(TM) Class Libraries will
CREATE application
INDEX SalaryIndex
ON Employee
(Salary)
give you insight into the power of Python and the know-how to put it to work.
"""

statement.executeUpdate(create_department)
raw_input("Department Table Defined hit enter to continue")

777

statement.executeUpdate(create_employee)
Python Programming with the Java Class Libraries: A Tutorial for Building
raw_input("Employee
Table Applications
Defined with
hit
enter to continue")
Web and Enterprise
Jython
By Richard Hightower

statement.executeUpdate(alter_table)
raw_input("Employee
altered by adding a Phone column.")
Publisher:table
Addison Wesley
Pub Date: June 28, 2002

statement.executeUpdate(add_index)
ISBN: 0-201-61616-5
Table of
raw_input("Adding
a salary index to the Employee table.")

Pages: 640
Contents

connection.close()
Characterized by ease of use, richness of expression, and concise syntax, Python has

remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
Little
the two languages, whenInstantDB:
used in combination,A
ideal
for WebDifferent
and distributed enterprise
application development.
InstantDB v.3.12 doesn't support the CONSTRAINT clause or foreign keys, nor can it handle the ALTER TABLE statemen
This tutorial
begins withHere's
coverage
of some
the basics
of Python programming. Using
though the documentation
says otherwise.
its version
ofof
ddl.py
(InstantDB/ddl.py):
plenty of skill-building exercises and interactive programming sessions, this book will
from java.sql
helpimport
those new DriverManager
to programming develop an understanding of concepts and practical
from java.lang
import
Class programmers, the book demonstrates Python's breadth of
techniques.
For experienced
capabilities and shows the ways that Python interfaces with Java APIs for professional
Class.forName("jdbc.idbDriver")
application development.

url = "jdbc:idb=db_dev.prp"
Python Programming with the Java(TM) Class Libraries:
Tutorial for Building Web
connection=DriverManager.getConnection(url,
"",A "")
and
Enterprise
Applications
with
Jython
covers
important
topics
such as:
statement = connection.createStatement()
create_department = """
Fundamental programming concepts, including statements, expressions,
CREATE TABLE Department (
interpreters, and compilers
DeptID
INT
PRIMARY KEY,
Name
CHAR(20),
Python basics, including operators, string formatting, namespaces, classes, errors,
)
and exceptions
"""
create_employee Object-oriented
= """
programming concepts
CREATE TABLE Employee (
EmpID
PRIMARY KEY,
File input/output INT
Name
CHAR(20),
Python's intrinsic functions
DeptID
INT
NOT NULL,
Salary
INT,
Formatting,
parsing, and manipulating
strings
Phone
CHAR(20)
NOT NULL
)
Interfacing with the Java APIs and working with Java Streams
"""
Using Python and Java Swing to create GUIs

#Note that InstantDB does not understand foreign keys...


# "No understanding
ofwith
foreign
keys or referential integrity checking "
Working
SQL and JDBC(TM)
##
REMOVED:
CONSTRAINT DEPT_FK_KEY FOREIGN KEY (DeptID)
Python and Java applets
##
REFERENCES Department (DeptID)
add_index = """
In addition,
book contains instructions
for downloading
and installing the Python
CREATE
INDEXthe
SalaryIndex
ON Employee
(Salary)
language
and
the
Java
Development
Kit
(JDK).
Terminology,
definitions, explanations,
"""
and
numerous
code
samples
make
this
book
a
useful
learning
experience.
statement.executeUpdate(create_department)
raw_input("Department Table Defined hit enter to continue")
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
statement.executeUpdate(create_employee)
give you insight
into theDefined
power of Python
and the
know-how
put it to work.
raw_input("Employee
Table
hit
enter
to to
continue")

777

#We are not able to alter the table once created log bug with InstantDB folks
#statement.executeUpdate(alter_table)
#raw_input("Employee table altered by adding a Phone column hit enter to co

Python Programming with the Java Class Libraries: A Tutorial for Building

statement.executeUpdate(add_index)
Web and Enterprise Applications with Jython
raw_input("Adding
salary index to the Employee table - hit enter to
By Richard a
Hightower
continue")
connection.close()
Publisher: Addison Wesley
Pub Date: June 28, 2002

Try these exercises:

Table of
Contents

ISBN: 0-201-61616-5
Pages: 640

Runddl.py in both the Access and InstantDB directories. Note the differences.
Characterized by ease of use, richness of expression, and concise syntax, Python has
remained
a premier
programming
fornote
morethe
than
a decade, and is used by
Runddl.py with
your RDBMS
system
and JDBClanguage
driver, and
differences.
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
SQL Data Types
application development.
We've defined a fewThis
simple
tablesbegins
with the
module.
Nowoflet's
at the
different
fields that can
show up
tutorial
withddl.py
coverage
of some
thelook
basics
of Python
programming.
Using
in a table. Until now,plenty
we'veofbeen
using onlyexercises
two SQLand
datainteractive
types, CHAR
and INT.Table
17-1this
listsbook
many
more,
skill-building
programming
sessions,
will
most of which are similar
to those
and Python.
If you want
to know what
type holds,
an SQL
help those
newintoJava
programming
develop
an understanding
ofeach
concepts
and practical
reference can tell you.
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
Table 17-1. JDBC, Java, and Python Types
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and
Enterprise Applications with Jython
covers important topics such as:
JDBC
Java
Python

CHAR
String
String
Fundamental
programming
concepts,
including statements, expressions,
VARCHAR
String
String
interpreters, and compilers String
LONGVARCHAR String
NUMERIC
java.math.BigDecimal
java.math.BigDecimal
Python basics, including operators,
string formatting, namespaces, classes, errors,
DECIMAL
java.math.BigDecimal
java.math.BigDecimal
and exceptions
BIT
boolean
Integer
Object-oriented programming concepts
TINYINT
byte
Integer
SMALLINT
short
Integer
File input/output
INTEGER
int
Integer
Python's intrinsic functions
BIGINT
long
Integer
Formatting, parsing, and manipulating
REAL
float
Float strings
FLOAT
double
Float
Interfacing with the Java APIs and working with Java Streams
DOUBLE
double
Float
Using Python and Java Swingjarray
to create GUIs
BINARY
byte[]
as byte[](sequence)
VARBINARY
byte[]
jarray as byte[](sequence)
Working with SQL and JDBC(TM)
LONGVARBINARY byte[]
jarray as byte[](sequence)
Python
and
Java
applets
DATE
java.sql.Date
java.sql.Date
TIME
java.sql.Time
java.sql.Time
In addition, the book contains instructions for downloading and installing the Python
TIMESTAMP
java.sql.Timestamp
language and the Java Developmentjava.sql.Timestamp
Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Notice that the left column in the table is headed JDBC, not SQL. One reason for this is that SQL doesn't have a
LONGVARCHAR. InWhether
fact, each
vendor seems
to haveuser
its own
for this type,orsoa there's
youdatabase
are a sophisticated
computer
newname
to programming
seriousno one-toapplication
Programming
with the Java(TM) Class Libraries will
one mapping between
JDBC anddeveloper,
SQL (butPython
what there
is is close enough).
give you insight into the power of Python and the know-how to put it to work.

Creating Fields with DDL

777

Let's illustrate how DDL creates fields of each type first in Microsoft Access (Access\DDL2.py).

from java.sqlPython
import
DriverManager
Programming
with the Java Class Libraries: A Tutorial for Building
from java.lang
Class
Webimport
and Enterprise
Applications with Jython
Class.forName('sun.jdbc.odbc.JdbcOdbcDriver')
By Richard Hightower
url="jdbc:odbc:db_dev"
Publisher: Addison Wesley
connection=DriverManager.getConnection(url,
"", "")
Pub Date: June 28, 2002
statement = connection.createStatement()
ISBN: 0-201-61616-5

Table of

Pages: 640

Contents
create_type_table1
= """
CREATE Characterized
TABLE TypeTable1
by ease of use,(richness of expression, and concise syntax, Python has

remained a premier programming language for more than a decade, and is used by
_bit and professionals
BIT,
novices
alike. In particular, its close relationship to Java(TM) makes
_int
INT,
the
two languages, when
used in combination, ideal for Web and distributed enterprise
_smallint
SMALLINT,
application
development.

_integer

INTEGER,

_numeric
NUMERIC,
This
tutorial begins with
coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
_char
CHAR(200),
help
those new to programming
develop an understanding of concepts and practical
_varchar
VARCHAR(200),
techniques.
For experienced
programmers, the book demonstrates Python's breadth of
_real and showsREAL,
capabilities
the ways that Python interfaces with Java APIs for professional
_float
FLOAT,
application development.
_double

DOUBLE,

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and
Enterprise Applications
with Jython covers important topics such as:
_binary
BINARY(200),

_varbinary

VARBINARY(200),

Fundamental programming
_date
DATE, concepts, including statements, expressions,
interpreters, andTIME,
compilers
_time
_timestamp
TIMESTAMP
Python basics, including operators, string formatting, namespaces, classes, errors,

)
and exceptions
"""
statement.executeUpdate(create_type_table1)
Object-oriented programming concepts

File input/output
The statement defined here creates every SQL type that MSAccess supports:
Python's intrinsic functions

create_type_table1 = """
CREATE TABLE
TypeTable1
( manipulating strings
Formatting,
parsing, and
the Java APIs and working with Java Streams
_bitInterfacing with BIT,
_int
INT,
Using Python and
Java Swing to create GUIs
_smallint
SMALLINT,
_integer
INTEGER,
Working with SQL and JDBC(TM)
_numeric
NUMERIC,
Python and Java applets

_char
CHAR(200),
_varchar
VARCHAR(200),
In addition, the book contains
instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
_real
REAL,
and
numerous code samples
make this book a useful learning experience.

_float

FLOAT,

_double
DOUBLE,computer user new to programming or a serious
Whether
you are a sophisticated
application developer, Python Programming with the Java(TM) Class Libraries will
_binary
BINARY(200),
give
you insight into the
power of Python and the know-how to put it to work.
_varbinary

777
_date
_time

VARBINARY(200),
DATE,
TIME,

)
"""

_timestamp
TIMESTAMP
Python
Programming
with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

JDBC'sLONGVARCHAR
and LONGVARBINARY aren't supported by standard SQL. Again, each vendor has
Publisher: Addison Wesley
its own names for these types. MSAccess supports them under the names LONGCHAR and LONGBINARY and
Pub Date: June 28, 2002
creates tables with them.
ISBN: 0-201-61616-5
Table of
Pages:
create_type_table2
= 640
"""
Contents

CREATE TABLE TypeTable2 (


Characterized
by ease of use, richness
of expression, and concise syntax, Python has
_longvarbinary
LONGBINARY,
remained
a
premier
programming
language
for more than a decade, and is used by
_longvarchar LONGCHAR
novices
and
professionals
alike.
In
particular,
its close relationship to Java(TM) makes
)

the two languages, when used in combination, ideal for Web and distributed enterprise
"""
application development.
statement.executeUpdate(create_type_table2)
raw_input("Create a type table 2")

This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help types
those not
newsupported
to programming
developInanfact,
understanding
practical
There are three standard
by MSAccess.
if you try toof
runconcepts
any codeand
with
them, JDBC
techniques.
For
experienced
programmers,
the
book
demonstrates
Python's
breadth of
will throw an exception. Here's an example (from ddl2.py):
capabilities and shows the ways that Python interfaces with Java APIs for professional
application=development.
create_type_table3
"""

CREATE TABLE TypeTable2 (


Python
Programming with
the Java(TM) Class Libraries: A Tutorial for Building Web
_decimal
DECIMAL,
and
Enterprise
Applications
with Jython
covers important topics such as:
_tinyint
TINYINT,
_bigint
BIGINT
)
Fundamental programming concepts, including statements, expressions,

"""
interpreters, and compilers
statement.executeUpdate(create_type_table3)

Python basics, including operators, string formatting, namespaces, classes, errors,


Notice that the third table, type_table3
and exceptions , isn't created. Here's Access/ddl2.py in its entirety:

from java.sql import


DriverManager
Object-oriented
programming concepts
from java.lang import Class
File input/output

Class.forName('sun.jdbc.odbc.JdbcOdbcDriver')
Python's intrinsic functions

url="jdbc:odbc:db_dev"
Formatting, parsing, and manipulating strings "", "")
connection=DriverManager.getConnection(url,
statement = connection.createStatement()

Interfacing with the Java APIs and working with Java Streams

create_type_table1
= """
Using Python and Java Swing to create GUIs
CREATE TABLE TypeTable1 (
Working with SQL and JDBC(TM)

_bit
BIT,
_intPython and JavaINT,
applets
_smallint
SMALLINT,
In_integer
addition, the book contains
instructions for downloading and installing the Python
INTEGER,
language
and the Java NUMERIC,
Development Kit (JDK). Terminology, definitions, explanations,
_numeric
and numerous code samples make this book a useful learning experience.

_char

CHAR(200),

Whether
you are a sophisticated
computer user new to programming or a serious
_varchar
VARCHAR(200),
application developer, Python Programming with the Java(TM) Class Libraries will
give
you insight into the
power of Python and the know-how to put it to work.
_real
REAL,

_float
_double
_binary
_varbinary

777

FLOAT,
DOUBLE,
BINARY(200),
VARBINARY(200),

_dateProgrammingDATE,
Python
with the Java Class Libraries: A Tutorial for Building
_time
TIME,
Web
and Enterprise Applications
with Jython
_timestamp
By
Richard Hightower TIMESTAMP
)
"""

Publisher: Addison Wesley


Pub Date: June 28, 2002

create_type_table2
= 0-201-61616-5
"""
ISBN:
Table
of
CREATE
TABLE
TypeTable2
(

Pages: 640
Contents
_longvarbinary
LONGBINARY,
_longvarchar
LONGCHAR
Characterized by ease of use, richness of expression, and concise syntax, Python has
)
remained a premier programming language for more than a decade, and is used by
"""
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise

create_type_table3
"""
application=development.
CREATE TABLE TypeTable2 (
_decimal
DECIMAL,
This
tutorial begins with
coverage of some of the basics of Python programming. Using
_tinyint
plenty
of skill-buildingTINYINT,
exercises and interactive programming sessions, this book will
_bigint
BIGINT develop an understanding of concepts and practical
help
those new to programming
)
techniques. For experienced programmers, the book demonstrates Python's breadth of
"""
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.

statement.executeUpdate(create_type_table1)
Python Programming
with the 1")
Java(TM) Class Libraries: A Tutorial for Building Web
raw_input("Create
a type table
and Enterprise Applications with Jython covers important topics such as:

statement.executeUpdate(create_type_table2)
raw_input("Create a type table 2")

Fundamental programming concepts, including statements, expressions,


interpreters, and compilers
statement.executeUpdate(create_type_table3)

raw_input("CreatePython
a type
table 3")
basics, including operators, string formatting, namespaces, classes, errors,
and exceptions

connection.close()

Object-oriented programming concepts

InstantDB
File input/output

Type Support

intrinsic
functions does. In the following code (InstantDB/ddl2.py),
InstantDB supports Python's
fewer types
than MSAccess
the types it does support are shown in type_table1. Those it supports but for which it has no
Formatting, parsing, and manipulating strings
standard SQL names are shown in type_table2.
Interfacing with the Java APIs and working with Java Streams

from java.sql import DriverManager


from java.lang
Class
Usingimport
Python and
Java Swing to create GUIs
Class.forName("jdbc.idbDriver")
Working with SQL and JDBC(TM)
url = "jdbc:idb=db_dev.prp"
Python and Java applets

connection=DriverManager.getConnection(url, "", "")


In addition,
the book contains instructions for downloading and installing the Python
statement
= connection.createStatement()
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code
create_type_table1
= samples
""" make this book a useful learning experience.

CREATE TABLE TypeTable1 (

Whether you are a sophisticated computer user new to programming or a serious


application
developer, Python Programming
_tinyint
TINYINT, with the Java(TM) Class Libraries will
give you insight
into
the
power
of Python and the know-how to put it to work.
_smallint
SMALLINT,

_integer
_int
_numeric
_decimal

777

INTEGER,
INT,
NUMERIC,
DECIMAL,

Python Programming with the Java Class Libraries: A Tutorial for Building
CHAR(200),
Web and_char
Enterprise Applications
with Jython
_varchar
VARCHAR(200),
By Richard Hightower

_float
Publisher:
Addison Wesley

FLOAT,
_double
Pub Date: June 28, 2002 DOUBLE,
_binary
BINARY(200),
ISBN: 0-201-61616-5
_varbinary
VARBINARY(200),
Pages: 640

Table of
Contents

_date
DATE,of expression, and concise syntax, Python has
Characterized
by ease of use, richness
) remained a premier programming language for more than a decade, and is used by

"""
novices and professionals alike. In particular, its close relationship to Java(TM) makes
create_type_table2
"""used in combination, ideal for Web and distributed enterprise
the two languages,=when
CREATE
TABLE
TypeTable2
(
application development.
_longvarbinary
LONGVARBINARY,
) This tutorial begins with coverage of some of the basics of Python programming. Using
"""
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical

create_type_table3
= """ programmers, the book demonstrates Python's breadth of
techniques. For experienced
CREATE
TABLE
TypeTable2
(
capabilities
and shows
the ways that Python
interfaces with Java APIs for professional
_real
REAL,
application development.
_bit
BIT,
_time
TIME, Class Libraries: A Tutorial for Building Web
Python Programming
with the Java(TM)
_timestamp
TIMESTAMP,
and Enterprise
Applications with
Jython covers important topics such as:
_bigint
BIGINT,
_longvarchar LONGVARCHAR
Fundamental
programming concepts, including statements, expressions,
)
interpreters, and compilers
"""
Python basics, including operators, string formatting, namespaces, classes, errors,

statement.executeUpdate(create_type_table1)
and exceptions
raw_input("Create a type table 1")
statement.executeUpdate(create_type_table2)
Object-oriented programming concepts
raw_input("Create a type table 2")
File input/output

statement.executeUpdate(create_type_table3)
Python's intrinsic
functions
raw_input("Create
a type
table 3")
Formatting, parsing, and manipulating strings
connection.close()
withbythe
Java APIs
andthe
working
with
Java Streams
Strangely, the types Interfacing
not supported
InstantDB
aren't
ones not
supported
by MSAccess. In
other words, one unsupported list isn't a subset of another unsupported list. Fortunately, the most
Using Python and Java Swing to create GUIs
common SQL types are supported by both.
Working with SQL and JDBC(TM)
Try these exercises:

Python and Java applets


Study and runIn
either
the MSAccess
or the InstantDB
version
of ddl2.py, depending
on the
addition,
the book contains
instructions
for downloading
and installing
thedatabase
Python type
you're workinglanguage
with. Note
and similarities.
andthe
thedifferences
Java Development
Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Locate the JDBC drivers to the RDBMS system you use regularly. Create a database, run the dml2.sql
scripts againstWhether
it, and make
changes
as necessary.
Note the
differences
and similarities.
Let me know your
you are
a sophisticated
computer
user
new to programming
or a serious
results via email.
I'd
like
a
comparison
for
each
type
of
database
(DBw,
DBASE,
Paradox,
Oracle,
application developer, Python Programming with the Java(TM) Class Libraries
will
MySQL, etc.).give
Stateyou
theinsight
versioninto
number
and
complete
product
name
along
with
the
JDBC
driver
the power of Python and the know-how to put it to work.
information.

777

SQL Data Manipulation Language

SQL's Data Manipulation


Language
(DML) with
defines
theJava
formatClass
of data
by insertion,
selection,
Python
Programming
the
Libraries:
A Tutorial
forupdating,
Buildingand
deletion. The four primary
DML
statementsApplications
are INSERTwith
,SELECT
,UPDATE, and DELETE, which we'll look
Web and
Enterprise
Jython
Richard Hightower
at individually in theBy
following
sections.
The very first exercise inPublisher:
this chapter
illustrated
all of these statements. Here we'll see them at work in a little
Addison
Wesley
more advanced databasePub
structure,
continuing
with
Date: June 28, 2002 our Employee and Department table examples.
ISBN: 0-201-61616-5

Table of
Insert

Pages: 640

Contents

If tables are like classes


in Python, by
then
rows
are like
instances.
Since the and
INSERT
inserts has
values into
Characterized
ease
of use,
richness
of expression,
concisestatement
syntax, Python
a premiertoprogramming
languagethat
for more
than aan
decade,
andofisaused
by
a table, we can thinkremained
of it as analogous
calling a constructor,
is, creating
instance
record.
novices and professionals alike. In particular, its close relationship to Java(TM) makes
INSERT takes the following
form:
the two languages,
when used in combination, ideal for Web and distributed enterprise
application development.

INSERT INTO table_name


(field_name1,
field_name2,
This tutorial begins
with coverage of ...)
some of the basics of Python programming. Using
VALUES
plenty of skill-building exercises and interactive programming sessions, this book will
(value1,
value2,
...)
help those
new to programming
develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
Here it's adding values
to the Employee
table:
capabilities
and shows
the ways that Python interfaces with Java APIs for professional
application development.

INSERT INTO
Employee
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
(EmpID,
Name, Applications
DeptID, with
Salary)
and Enterprise
Jython covers important topics such as:
VALUES
(10507, 'Bob Jones', '1', 10)
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers

Select

Python basics, including operators, string formatting, namespaces, classes, errors,


TheSELECT statement selects rows from a table. We've already used it, so I won't belabor it at this point.
and exceptions
Here's its form:
Object-oriented programming concepts

SELECT
table.fieldFile[as
alias]
input/output
FROM
table [as alias]
Python's intrinsic functions
[WHERE. criteria]
Formatting,...]
parsing,[HAVING
and manipulating
strings
[GROUP BY table.field,
criteria]
[ORDER BY table.field, ...]

Interfacing with the Java APIs and working with Java Streams
TheORDER BY clause sorts the query results. The GROUP BY and HAVING clauses group items for
Using
and Java Swing to create GUIs
aggregate functions, such as
sumPython
.
Working with SQL and JDBC(TM)
Here's a SELECT example:
Python and Java applets
SELECT
Name, Salary
In addition, the book contains instructions for downloading and installing the Python
FROM Employee
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
WHERE
and numerous code samples make this book a useful learning experience.
(Salary > 10 )
and
Whether you are a sophisticated computer user new to programming or a serious
(DeptIDapplication
= 10) developer, Python Programming with the Java(TM) Class Libraries will
ORDER BY Namegive you insight into the power of Python and the know-how to put it to work.
which can be rewritten as

777

SELECT Name, Salary FROM Employee WHERE (Salary > 10 ) and (DeptID == 10)
ORDER BY Name

Python Programming with the Java Class Libraries: A Tutorial for Building
WithSELECT you can
join tables to get columns from more than one table at a time. When you do this, you'll
Web and Enterprise Applications with Jython
probably want to useBy
anRichard
alias because
the tables to be joined may have the same fields; aliasing allows such
Hightower
fields to be used in the WHERE clause.
Publisher: Addison Wesley
The next example gets the
employee's name, salary, and department. Since the department name is stored in the
Pub
Date:
28, 2002
Department table, we have to
join June
Department
and Employee for the statement to work.
Table of

ISBN: 0-201-61616-5

SELECT
Pages: 640
Contents
e.Name as emp_name,
e.Salary
as salary,
Characterized
by ease of use, richness of expression, and concise syntax, Python has
d.Name remained
as dept_name
a premier programming language for more than a decade, and is used by
FROM
novices and professionals alike. In particular, its close relationship to Java(TM) makes
Employee
as languages,
e,
the two
when used in combination, ideal for Web and distributed enterprise
Department
as development.
d
application
WHERE
This tutorial
begins with coverage
(e.DeptID
= d.DeptID)
and of some of the basics of Python programming. Using
plenty
of
skill-building
exercises
and interactive programming sessions, this book will
(e.Salary > 10 )
and
help
those
new
to
programming
develop
an understanding of concepts and practical
(e.DeptID = 10)

techniques. For experienced programmers, the book demonstrates Python's breadth of


The first part of the WHERE
clause
how
thethat
tables
are tointerfaces
be joined.with
It defines
our Employee
and
capabilities
andspecifies
shows the
ways
Python
Java APIs
for professional
Department tables with
the respective
aliases e and d because both tables have DeptID and Name fields.
application
development.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web

WHERE

(e.DeptID
= d.DeptID)
and
and Enterprise
Applications
with Jython covers important topics such as:
Without the aliases, we can't differentiate a department name and an employee name. Three field aliases are also
Fundamental
programming
expressions,
defined:emp_name ,salary
, and dept_name
. Ifconcepts,
we were including
to run thisstatements,
query via JDBC,
we'd have to use
compilers
the aliases for the columns interpreters,
returned, notand
their
names, in order to access the results.

Python
basics,
including
operators,
string formatting,
namespaces,
classes,
errors,
Notice the as in the first line
of the
SELECT
statement
(e.Name
as emp_name
). It's nice
to have
this
and
exceptions
syntax, although many programmers don't use it. Because it's optional, the following statement is equivalent to
the preceeding one:
Object-oriented programming concepts

SELECT
File input/outputemp_name,
e.Name
e.Salary
salary,
Python's intrinsic functions
d.Name
dept_name
FROM
Formatting, parsing, and manipulating strings
Employee
e,
Department Interfacing
d
with the Java APIs and working with Java Streams
WHERE
Python andand
Java Swing to create GUIs
(e.DeptID = Using
d.DeptID)
(e.Salary > 10 )
and
(e.DeptID = Working
10) with SQL and JDBC(TM)
I like using as.

Python and Java applets


In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

The ANSI SQL JOIN Clause

Publisher:
Addison
If the database has
a later version
ofWesley
ANSI SQL installed, you can use the JOIN clause to join
Pub Date: June 28, 2002
tables.

Table
of
SELECT
Contents

ISBN: 0-201-61616-5
Pages: 640

e.Name as emp_name,
e.Salary
asbysalary,
Characterized
ease of use, richness of expression, and concise syntax, Python has
d.Name
dept_name
remainedas
a premier
programming language for more than a decade, and is used by

FROM

novices and professionals alike. In particular, its close relationship to Java(TM) makes

Employee
as e when used in combination, ideal for Web and distributed enterprise
the two languages,
JOIN

application development.

Department as d
on begins
e.DeptID
= d.DeptID
This tutorial
with coverage
of some of the basics of Python programming. Using
WHERE

plenty of skill-building exercises and interactive programming sessions, this book will

(e.Salary
> to
10programming
) and develop an understanding of concepts and practical
help those new
(e.DeptID
==experienced
10)
techniques. For
programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
Because it makes
the syntax
is more modular and easier to read (it separates the WHERE clause
application
development.
from the rest of the statement), I suggest you use JOIN if you have the choice.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
Here's the lastand
statement
withApplications
the as syntax:
Enterprise
with Jython covers important topics such as:

SELECT
e.NameFundamental programming
emp_name,
concepts, including statements, expressions,
e.Salary
salary,
interpreters, and compilers
d.Name
dept_name
Python
basics,
including operators, string formatting, namespaces, classes, errors,
FROM
and
exceptions
Employee
e
JOIN
Object-oriented
programming concepts
Department
d
on e.DeptID = d.DeptID
File input/output
WHERE
(e.Salary
10 )functions
and
Python's>intrinsic
(e.DeptID = 10)
Formatting, parsing, and manipulating strings
Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs
Working with SQL and JDBC(TM)
Python and Java applets
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

INNER Join

Publisher:
AddisonJOIN
Wesleyif the JOIN clause is left by itself. However, MSAccess
Most databases assume
an INNER
makes no such assumption
you to specify an INNERJOIN like this:
Pub Date: and
Juneexpects
28, 2002

Table
of
SELECT
Contents

ISBN: 0-201-61616-5
Pages: 640

e.Name
as emp_name,
e.Salary
as
salary,
Characterized by ease of use, richness of expression, and concise syntax, Python has
d.Name
asprogramming
dept_name
remained a premier
language for more than a decade, and is used by

FROM

novices and professionals alike. In particular, its close relationship to Java(TM) makes

Employee
e used in combination, ideal for Web and distributed enterprise
the two languages,as
when
INNER JOIN
application development.
Department
as d
on e.DeptID
= d.DeptID
This tutorial
begins with coverage
of some of the basics of Python programming. Using
WHERE
plenty of skill-building exercises and interactive programming sessions, this book will
(e.Salary
> to
10programming
) and develop an understanding of concepts and practical
help those new
(e.DeptID
techniques.=For100)
experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
The four typesapplication
of JOIN are
INNER,OUTER,LEFT, and RIGHT. We're going to cover only
development.
INNERJOINs, which are probably the most common.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
By the way, you
join more
than one table
a timecovers
by adding
extra JOIN
andcan
Enterprise
Applications
withatJython
important
topics clauses.
such as: You can
find the exact syntax in a good SQL reference.

Update

Fundamental programming concepts, including statements, expressions,


interpreters, and compilers

Python the
basics,
including
formatting,
namespaces,
classes,
errors,
TheUPDATE statement modifies
fields
in a row.operators,
Its Pythonstring
equivalent
is setting
an attribute
of a class
and
exceptions
instance. UPDATE takes the form
Object-oriented programming concepts
UPDATE
table_name
File input/output
SET
field1=value1, field2=value2, ...
Python's intrinsic functions
[WHERE clause]
Formatting, parsing, and manipulating strings
Here's an example of using UPDATE to give an employee a raise:
Interfacing with the Java APIs and working with Java Streams

UPDATE
Employee Using Python and Java Swing to create GUIs
SET
Salary=11 Working with SQL and JDBC(TM)
WHERE
EmpID = 10507
Python and Java applets

In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
TheDELETE statement removes records from a table. Deleting a record is like setting all object references to
None (forcing the garbage
delete the object).
DELETE
takes
form
Whethercollector
you are to
a sophisticated
computer
user new
tothe
programming
or a serious

Delete

application developer, Python Programming with the Java(TM) Class Libraries will

DELETE
give you insight into the power of Python and the know-how to put it to work.
FROM
table_name
[WHERE clause]

777

Deleting an employee record looks like this:

Python Programming with the Java Class Libraries: A Tutorial for Building

DELETE FROM Web and Enterprise Applications with Jython


Employee
By Richard Hightower
WHERE
EmpID = 10507
Publisher: Addison Wesley
Pub Date: June 28, 2002
Laying off an entire department
looks like this:
Table of

ISBN: 0-201-61616-5

Pages: 640
DELETE
FROM
Contents
Employee
Characterized by ease of use, richness of expression, and concise syntax, Python has
WHERE
DeptID remained
= 100 a premier programming language for more than a decade, and is used by

Using DML

novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.

To show how DML This


works,
we'll begins
use it towith
insert
some departments
intobasics
our Department
table. Define aUsing
Python
tutorial
coverage
of some of the
of Python programming.
format string.
plenty of skill-building exercises and interactive programming sessions, this book will

help those new to programming develop an understanding of concepts and practical

d_insert = """
techniques. For experienced programmers, the book demonstrates Python's breadth of
INSERT INTO
capabilities and shows the ways that Python interfaces with Java APIs for professional
Department
application development.
(DeptID, Name)
VALUES Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
(%d,
'%s')Applications with Jython covers important topics such as:
and Enterprise
"""
Define a set of tuples, department
for sample departments.
Fundamentals,programming
concepts, including statements, expressions,
interpreters, and compilers

departments = (
(100, "Engineering"),
Python basics, including operators, string formatting, namespaces, classes, errors,
(200, "Marketing"),
and exceptions
(300, "Human Resources"),
Object-oriented programming concepts
(400, "Manufacturing")
) #End of departments
File input/output
Iterate through departments, and create rows in the Department table.
Python's intrinsic functions

for dept in departments:


Formatting, parsing,
and manipulating strings
insert = d_insert
% dept
print insert
Interfacing with the Java APIs and working with Java Streams
statement.executeUpdate(insert)
Using Python and Java Swing to create GUIs
Now we'll add employees to the Employee table. Define an insert format string.

e_insert = """ Working with SQL and JDBC(TM)


INSERT INTOPython and Java applets
Employee
DeptID,
Salary,
Phone)and installing the Python
In(EmpID,
addition, theName,
book contains
instructions
for downloading
VALUES language and the Java Development Kit (JDK). Terminology, definitions, explanations,
(%d,
'%s',
%d,
'%s')
and
numerous
code%d,
samples
make
this book a useful learning experience.
"""
Whether you are a sophisticated computer user new to programming or a serious
Define a tuple with some
employees
row
data. Programming with the Java(TM) Class Libraries will
application
developer,
Python
give you insight into the power of Python and the know-how to put it to work.

employees = (
(1000, "Rick Hightower", 100, 5, "555-1212"),
(1001, "Ricky Martin",
200, 10, "555-1213"),
(1002, "Adam Carr",
100, 6, "555-1214"),

777

(1003,Python
"BobProgramming
Deanna", with the100,
Java15,
Class"555-1215"),
Libraries: A Tutorial for Building
(1004,Web
"Tim
Simeonov",
100,
16,
"555-1216"),
and Enterprise
Applications
with
Jython
(1005,ByRichard
"Scott
Faurbach", 100, 14, "555-1217"),
Hightower
(1006, "Mary Basset",
300, 5, "555-1218"),
(1007, "Missy
Carr",
Publisher: Addison
Wesley 400, 5, "555-1219"),
(1008, "Paul
400, 5, "555-1220"),
Pub Date:Ganz",
June 28, 2002
(1009, "Tom
Jones",
400, 5, "555-1221"),
ISBN: 0-201-61616-5
Table (1010,
of
"Martha
Pena",
200, 25, "555-1222"),

Pages: 640
Contents
(1011, "John Souza",
200, 15, "555-1223")
) #End of employees
Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
Add the data in the employees tuple to the Employee table.
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
for emp in employees:
development.
insert application
= e_insert
% emp

print insert
This tutorial begins with coverage of some of the basics of Python programming. Using
statement.executeUpdate(insert)

plenty of skill-building exercises and interactive programming sessions, this book will
Try these exercises: help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
development. and access\connect.py; run access\dml_insert.py.
Study the codeapplication
in access\dml_insert.py

Programming with theand


Java(TM)
Class Libraries:run
A InstantDB\dm
Tutorial for Building
Web
Study the codePython
in instantDB\dml_insert.py
instantDB\connect.py;
l_insert.py.
and Enterprise Applications with Jython covers important topics such as:
Theconnect.py file varies depending on whether you connect to an ODBC database (such as MSAccess) or a
pure Java database such as InstantDB. Here are both versions:
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
Access\connect.py:

from java.sql import


DriverManager
Python basics,
including operators, string formatting, namespaces, classes, errors,
from java.lang import
Class
and exceptions
Object-oriented programming concepts
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver")
url = "jdbc:odbc:db_dev"
File input/output

connection=DriverManager.getConnection(url, "", "")


Python's intrinsic functions
statement = connection.createStatement()
InstantDB\connect.py:

Formatting, parsing, and manipulating strings


Interfacing with the Java APIs and working with Java Streams

from java.sql import DriverManager


from java.lang import
Class
Using Python
and Java Swing to create GUIs

Class.forName("jdbc.idbDriver")
Working with SQL and JDBC(TM)
url = "jdbc:idb=db_dev.prp"
Python and Java applets
connection=DriverManager.getConnection(url,
"", "")
statement = connection.createStatement()
In addition, the book contains instructions for downloading and installing the Python
language
and the Java
Terminology,
definitions,applies
explanations,
Inserting data is the same
in InstantDB
andDevelopment
MSAccess, soKit
the(JDK).
following
code (dml_insert.py)
to both.
code samples
(The JDBC-specific and
codenumerous
is highlighted
in bold.) make this book a useful learning experience.
you*are a sophisticated
computer
user new to programming
or a serious object
from connect Whether
import
# imports
connection
and statement
application developer, Python Programming with the Java(TM) Class Libraries will
d_insert = """
give you insight into the power of Python and the know-how to put it to work.

INSERT INTO
Department
(DeptID, Name)
VALUES

777

(%d,
'%s')
Python
Programming with the Java Class Libraries: A Tutorial for Building
"""

Web and Enterprise Applications with Jython


By Richard Hightower

e_insert = """
INSERT INTO
Publisher: Addison Wesley
Employee
Pub Date: June 28, 2002
(EmpID,
Name, DeptID, Salary, Phone)
ISBN: 0-201-61616-5
Table
of
VALUES

Pages: 640
Contents
(%d, '%s', %d, %d, '%s')
"""
Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by

departments =novices
( and professionals alike. In particular, its close relationship to Java(TM) makes
(100, "Engineering"),
the two languages, when used in combination, ideal for Web and distributed enterprise
(200, "Marketing"),
application development.
(300, "Human Resources"),
(400, "Manufacturing")
This tutorial begins with coverage of some of the basics of Python programming. Using
) #End of departments
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical

employees = (techniques. For experienced programmers, the book demonstrates Python's breadth of
(1000, capabilities
"Rick Hightower",
5, "555-1212"),
and shows the ways100,
that Python
interfaces with Java APIs for professional
(1001, application
"Ricky development.
Martin",
200, 10, "555-1213"),
(1002, "Adam Carr",
100, 6, "555-1214"),
Java(TM)
Class
Libraries: A Tutorial for Building Web
(1003, Python
"BobProgramming
Deanna",with the 100,
15,
"555-1215"),
Enterprise
Applications with
Jython16,
covers
important topics such as:
(1004, and
"Tim
Sieonov",
100,
"555-1216"),
(1005, "Scott Faurbach", 100, 14, "555-1217"),
(1006, "Mary Basset",
300, 5, "555-1218"),
Fundamental
programming
concepts,
including statements, expressions,
(1007, "Missy
Carr",
400,
5, "555-1219"),
interpreters,
and compilers
(1008, "Paul
Ganz",
400, 5, "555-1220"),
(1009, "TomPython
Jones",
400, 5, "555-1221"),
basics, including operators, string formatting, namespaces, classes, errors,
(1010, "Martha
Pena",
200, 25, "555-1222"),
and exceptions
(1011, "John Souza",
200, 15, "555-1223")
) #End of employees
Object-oriented programming concepts
hit = " - hit enter
to continue - "
File input/output
raw_input ("testing inserts" + hit)
Python's intrinsic functions

raw_input("Adding departments" + hit)


Formatting, parsing, and manipulating strings

for dept in departments:


Interfacing with the Java APIs and working with Java Streams
insert = d_insert % dept
print insert
Using Python and Java Swing to create GUIs
statement.executeUpdate(insert)
Working with SQL and JDBC(TM)

raw_input("Adding employees" + hit)


Python and Java applets

for emp in employees:


the book
insert In=addition,
e_insert
% contains
emp instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
print insert
and numerous code samples make this book a useful learning experience.
statement.executeUpdate(insert)
Whether you
are a sophisticated
raw_input("testing
select"
+ hit)computer user new to programming or a serious

application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.
connection.close()
Notice that the first statement imports all of the objects from the connect.py module. This is so the module will
hold all of the code needed for connecting. To connect to another database, just modify connect.py accordingly.

777

Using SELECT (with


Multiple
JOIN Statements)
Python
Programming
with the Java

Class Libraries: A Tutorial for Building


Web and Enterprise Applications with Jython
SELECTBy
statement
to join tables. The code that follows (Access\dml_select.py) shows a multi-table
Richard Hightower

Let's use a
join with MSAccess.

Publisher: Addison Wesley

from connect import


*
Pub Date: June 28, 2002
Table =of """
select

Contents
SELECT

ISBN: 0-201-61616-5
Pages: 640

e.Name

as emp_name,

Characterized by ease of use, richness of expression, and concise syntax, Python has
e.Salary
as salary,
remained a premier programming language for more than a decade, and is used by
d.Name
as dept_name
novices and professionals alike. In particular, its close relationship to Java(TM) makes
FROM the two languages, when used in combination, ideal for Web and distributed enterprise
Employee
as e
application development.

INNER JOIN
Department
as d of some of the basics of Python programming. Using
This
tutorial begins with coverage
on
e.DeptID
plenty of skill-building exercises=andd.DeptID
interactive programming sessions, this book will
WHERE help those new to programming develop an understanding of concepts and practical
(e.Salary
> 10 )programmers,
and
techniques.
For experienced
the book demonstrates Python's breadth of
(e.DeptID
= 100)
capabilities
and shows
the ways that Python interfaces with Java APIs for professional
"""

application development.

results = statement.executeQuery(select)
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

emp_name="emp_name"
salary="salary"
Fundamental programming concepts, including statements, expressions,
dept_name="dept_name"
interpreters, and compilers

format = "%(emp_name)s,\t\t%(dept_name)s,\t\t%(salary)3.2f"

Python basics, including operators, string formatting, namespaces, classes, errors,


and exceptions

while results.next():
dict = {} Object-oriented programming concepts
dict[emp_name]
=
results.getString(emp_name)
dict[salary]
results.getInt(salary)
File input/output =
dict[dept_name]
=
results.getString(dept_name)
print format
% intrinsic
dict functions
Python's
Formatting, parsing, and manipulating strings
connection.close()
Interfacing
with theSELECT
Java APIs
Here's the InstantDB version
of a multi-table
: and working with Java Streams

Using *Python and Java Swing to create GUIs


from connect import
select = """
Working with SQL and JDBC(TM)
SELECT
e.Name
as emp_name,
Python and Java applets
e.Salary
as salary,
d.Name
as instructions
dept_name
In addition, the book contains
for downloading and installing the Python
FROM language and the Java Development Kit (JDK). Terminology, definitions, explanations,
asmake
e this book a useful learning experience.
andEmployee
numerous code samples
JOIN
Department
as d computer user new to programming or a serious
Whether
you are a sophisticated
on
e.DeptID
= d.DeptID
application developer, Python Programming
with the Java(TM) Class Libraries will
WHERE give you insight into the power of Python and the know-how to put it to work.
(e.Salary > 10 ) and
(e.DeptID = 100)
"""

777

results = statement.executeQuery(select)
Python Programming with the Java Class Libraries: A Tutorial for Building
...
Web and Enterprise Applications with Jython
... (The restByRichard
is the
same as before)
Hightower
The two versions are nearly
identical except that the JOIN'sINNER modifier has been left off in the InstantDB
Publisher: Addison Wesley
code because it's assumed. (According to the documentation, JOIN should work when the modifier is supplied.)
Pub Date: June 28, 2002
Also, I used the executeQuery() method of the statement object for the SELECT statement, whereas I
ISBN: 0-201-61616-5
used the
executeUpdate()
method for the INSERT statement. Always use the former for SELECTs and
Table
of

Pages: 640
Contents
the latter
for just about everything elseupdates, inserts, deletes, and any DDL operations.
executeQuery() returns a result set for the query, and executeUpdate() returns the number of
Characterized by ease of use, richness of expression, and concise syntax, Python has
rows affected by any table modifications.
remained a premier programming language for more than a decade, and is used by
novices
and professionals
alike.
particular,
its close relationship
to Java(TM)
As an exercise, run the
dml_select
module for one
orIn
both
of the databases
(ODBC or pure
Java). Trymakes
each of the
the
two
languages,
when
used
in
combination,
ideal
for
Web
and
distributed
followingSELECT statements. Determine which ones work as expected and which ones don't. enterprise
application development.
No INNERmodifer:
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
SELECT
programming develop an understanding of concepts and practical
e.Namehelp those new
astoemp_name,
techniques.
For
experienced
e.Salary
as salary,programmers, the book demonstrates Python's breadth of
capabilities
and
the ways that Python interfaces with Java APIs for professional
d.Name
as shows
dept_name
application development.
FROM

Employee
JOIN

as e

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise
with Jython covers important topics such as:
Department
asApplications
d

on e.DeptID = d.DeptID
WHERE

Fundamental programming concepts, including statements, expressions,

(e.Salary interpreters,
> 10 ) and
andcompilers
(e.DeptID = 100)

Python basics, including operators, string formatting, namespaces, classes, errors,

INNERmodifier with assyntax


for aliases:
and exceptions
SELECT

Object-oriented programming concepts

e.Name
emp_name,
e.Salary File input/output
salary,
d.Name
dept_name
FROM

Python's intrinsic functions

Employee
e
Formatting, parsing, and manipulating strings
INNER JOIN
Department
d
Interfacing with
Java APIs and working with Java Streams
on e.DeptID
= the
d.DeptID
WHERE
Using Python and Java Swing to create GUIs
(e.Salary > 10 ) and
(e.DeptID Working
= 100)
with SQL and JDBC(TM)
INNERmodifier without asPython
syntax:and Java applets
SELECT

In addition, the book contains instructions for downloading and installing the Python

e.Namelanguage andemp_name,
the Java Development Kit (JDK). Terminology, definitions, explanations,
e.Salary
salary,
and numerous
code samples make this book a useful learning experience.
d.Name
dept_name
FROM

Whether you are a sophisticated computer user new to programming or a serious

Employee
e
application developer,
Python Programming with the Java(TM) Class Libraries will
INNER JOIN give you insight into the power of Python and the know-how to put it to work.
Department
d
on e.DeptID = d.DeptID
WHERE
(e.Salary > 10 ) and

777

(e.DeptID = 100)
Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython

Old-styleJOIN(no JOIN
clause):
By Richard
Hightower

SELECT

Publisher: Addison Wesley

e.Name
emp_name,
June 28, 2002
e.SalaryPub Date:salary,
ISBN: 0-201-61616-5
dept_name
Table d.Name
of

Pages: 640
FROM
Contents
Employee
e,
Characterized
Department
d by ease of use, richness of expression, and concise syntax, Python has
remained
a
premier
programming language for more than a decade, and is used by
WHERE
novices
and
professionals
In particular, its close relationship to Java(TM) makes
(e.DeptID = d.DeptID) alike.and
the
two
languages,
when
used
in
combination, ideal for Web and distributed enterprise
(e.Salary > 10 )
and
application
development.
(e.DeptID = 100)
Thisforms
tutorial
with coverage
of some of Then
the basics
of Python
programming.
See if you can run these
onbegins
both MSAccess
and InstantDB.
run them
against
your own Using
plenty
of
skill-building
exercises
and
interactive
programming
sessions,
this book will
database/JDBC driver pair.
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
Using DELETE
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
The following code (dml_delete.py) deletes the marketing department from the Department table. It's the same
for MSAccess and InstantDB.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

from connect import *


#import statement and connection objects.
from java.lang import Exception
Fundamental programming concepts, including statements, expressions,

marketingID = 200interpreters, and compilers


delete = "delete from Department where DeptID = %d" % marketingID
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
# Try to delete
the record.
# Close connection no matter what!
Object-oriented programming concepts

try:
#
#
#
try:

File input/output
Try
to delete the record.
If
an
exception occurs
Python's intrinsic functions
print out the exception's message.
Formatting, parsing, and manipulating strings

statement.executeUpdate(delete)
Interfacing with the Java APIs and working with Java Streams

except Exception, e:
Using "Unable
Python and Java
to create
GUIs
print
to Swing
delete
marketing"+e.message
finally:

Working with SQL and JDBC(TM)


Python and Java applets

connection.close()

In addition, the book contains instructions for downloading and installing the Python
Notice the try...except and try...finally blocks. try...finally makes sure the
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
connection is closed if there's an exception. try...except prints out the exception message. It's a good
and numerous code samples make this book a useful learning experience.
idea to wrap database calls in a try...finally block to ensure a closed connection.
Whether you are a sophisticated computer user new to programming or a serious

Referential Integrity
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.
As an exercise, see if you can run dml_delete.py against both InstantDB and MSAccess. You'll notice that it
doesn't work with MSAccess but does work with InstantDB. MSAccess's behavior is preferred. Why?

777

Because the operation should fail to preserve referential integrity. Essentially, if you delete the department record

and there are still employees


in that department,
your
JOINLibraries:
SELECT statements
working. If
Python Programming
with
themultiple
Java Class
A Tutorialwill
for stop
Building
that happens, you'll get
thisand
message:
Web
Enterprise Applications with Jython
By Richard Hightower

Unable to delete marketing [Microsoft][ODBC Microsoft Access 97 Driver]. The


record cannot be
deleted or changed because table 'Employee' includes related
Publisher: Addison Wesley
records.
Pub Date: June 28, 2002

0-201-61616-5
whichTable
meansofthat, as long asISBN:
the Employee
table contains records for marketing employees, you can't delete the

Pages: 640
marketing
record in the Department table. This is how MSAccess maintains its referential integrity.
Contents

Characterized
by ease
of use, should
richnessclear
of expression,
If you're a little confused,
the following
exercises
things up: and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
Study and runthe
dml_delete.py
in both
theused
MSAccess
and InstantDB
directories.
two languages,
when
in combination,
ideal for
Web and distributed enterprise
application development.
Study and run dml_select2.py in both. This module selects a group of employees who are in the marketing
department, i.e.,
whose
DeptID
is equal
to 200.ofWhat
whenof
you
run this
query against
the
This
tutorial
begins with
coverage
somehappens
of the basics
Python
programming.
Using
InstantDB database?
Against
the MSAccess
database?
Which of
the two exhibits
the correct
behavior?
plenty of
skill-building
exercises
and interactive
programming
sessions,
this book
will
help those new to programming develop an understanding of concepts and practical
Write a query techniques.
or a set of queries
that will work
with eitherthe
MSAccess
or InstantDB
after dml_delete
For experienced
programmers,
book demonstrates
Python's
breadth of is run
on both.
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web

InstantDB/MSAccess
Support
for Referential
and Enterprise Applications with Jython
covers important
topics such as:
Integrity

Fundamental programming concepts, including statements, expressions,


Because it's a lightweight,
InstantDB
makes no claim of supporting referential integrity. I don't
interpreters,
and compilers
consider MSAccess a heavyweight, but it does provide some referential integrity support, as we've
Python basics, including operators, string formatting, namespaces, classes, errors,
just seen.
and exceptions
For the DELETE statement to work, we need to move every employee in marketing to a new departmentthat
Object-oriented
programming
concepts
is, change their DeptID to
one for an existing
department.
An alternative is to delete them from the Employee
table first (that is, lay themFile
all off).
input/output
Achieving Referential Integrity
with UPDATE
Python's intrinsic
functionsand DELETE

Formatting,
parsing,
and manipulating
What follows is an example
that lays off
some workers
and movesstrings
others to a different department via the
UPDATE and DELETE statements The code, dml_delete2.py, is the same for both MSAccess and InstantDB.
Interfacing
with
Java story.)
APIs and working with Java Streams
(Be sure to read the comments.
They tell
thethe
whole
Using *Python and Java Swing to create GUIs
from connect import
from java.lang import Exception
Working with SQL and JDBC(TM)

marketingID = 200Python and Java applets


mfgID = 400
engID = 100 In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,

# Move and
employees
whose
numerous code
samplessalary
make this is
bookless
a useful learning experience.
# than 10 and greater than 8
# to manufacturing.
Whether you are a sophisticated computer user new to programming or a serious
update1 = """application developer, Python Programming with the Java(TM) Class Libraries will
update give you insight into the power of Python and the know-how to put it to work.
Employee
set
DeptID=%d
where

777

salary
> 8 and salary
<= 10
Python Programming
with the Java
Class Libraries: A Tutorial for Building
""" % mfgID

Web and Enterprise Applications with Jython


By Richard Hightower

# Layoff employees whose salary


# is greater
than
16.
Publisher:
Addison
Wesley
#
Pub Date: June 28, 2002
delete1 = """
ISBN: 0-201-61616-5
Table
of
delete
fromPages: 640

Contents
Employee
where Characterized by ease of use, richness of expression, and concise syntax, Python has
salary
16 programming language for more than a decade, and is used by
remained a>premier
"""
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise

# Move application
employees
whose salary is less
development.
# than 16 and greater than 10
# to engineering.
adjust
their
to 10.
This tutorial beginsAlso
with coverage
of some
of thesalary
basics of Python
programming. Using
update2 = """plenty of skill-building exercises and interactive programming sessions, this book will
update help those new to programming develop an understanding of concepts and practical
Employee
techniques. For experienced programmers, the book demonstrates Python's breadth of
set
capabilities and shows the ways that Python interfaces with Java APIs for professional
DeptID=%d,
salary=10
application development.
where
Python Programming
withsalary
the Java(TM)
Class Libraries: A Tutorial for Building Web
salary
< 16 and
> 10
""" % engID and Enterprise Applications with Jython covers important topics such as:
#
#
#
delete2

Remove the Marketing department


programming
from the Fundamental
Department
table.concepts, including statements, expressions,
and compilers
It shouldinterpreters,
work this
time!
= "deletePython
from
Department
where DeptID = %d" % marketingID
basics, including operators, string formatting, namespaces, classes, errors,
and exceptions

#Try to delete the record.


#Close connection
no programming
matter what!
Object-oriented
concepts
try:

File input/output
intrinsic functions
# TryPython's
to delete
the record.
# If an exception occurs
Formatting,
and manipulating strings
# print
out parsing,
the exception's
message.

try:

Interfacing with the Java APIs and working with Java Streams

statement.executeUpdate(update1)
statement.executeUpdate(update2)
Using Python and Java Swing to create GUIs
statement.executeUpdate(delete1)
statement.executeUpdate(delete2)
Working with SQL and JDBC(TM)
except Exception,
e: applets
Python and Java

In addition,
the book contains
instructions
for downloading
installing the Python
print
"Unable
to delete
marketing"
+ and
e.getMessage()

finally:

language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.

connection.close()

Whether you are a sophisticated computer user new to programming or a serious


application developer, Python Programming with the Java(TM) Class Libraries will
give you insightininto
power of and
Python
and the know-how
to put
it to work.
As an exercise, run dml_delete2.py
boththeMSAccess
InstantDB.
Use either the
Microsoft
Access GUI or
the SQLBuilder GUI to look at the data. (For SQLBuilder, read the InstantDB documentation; also read the
following sidebar.)

777

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

Working with SQLBuilder

Publisher:
Addison Wesley
Here's how to work
with SQLBuilder:
Pub Date: June 28, 2002

1. Compile it.

Table of
Contents

ISBN: 0-201-61616-5
Pages: 640

C:\InstantDB\Examples\SQLBuilder>javac *.java

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship
to Java(TM) makes
C:\InstantDB\Examples\SQLBuilder>java
SQLBuilder
the two languages, when used in combination, ideal for Web and distributed enterprise
development.
Hit the application
Browse button,
and select the appropriate database property filefor example:
C:\JPython_book\scripts\chap17\InstantDB\db_dev.prp.
tutorial
begins with coverage of some of the basics of Python programming. Using
Hit the This
Connect
button.
plenty
of
skill-building
exercises and interactive programming sessions, this book will
Go to the Query tab.
help
those
new
to
programming
develop
an understanding
of concepts and practical
Select the Employee table from the Tables
dropdown
list.
techniques.
For
experienced
programmers,
the
book
demonstrates
Python's breadth of
Hit the Submit button.
capabilities
and
shows
the
ways
that
Python
interfaces
with
Java
APIs
for professional
Repeat steps 6 and 7 for the Department table.
application development.

2. Run it.

3.
4.
5.
6.
7.
8.

Programming with the Java(TM)


Class Libraries:
A Tutorial
Building
Web
Putting It AllPython
TogetherAdding
Database
Support
toforthe
Address
and Enterprise Applications with Jython covers important topics such as:
Book Application
Fundamental
including First,
statements,
expressions,
Now we're ready to add database
supportprogramming
to our addressconcepts,
book application.
though,
let's review the
application's main modules.interpreters, and compilers
Python basics, including operators, string formatting, namespaces, classes, errors,
exceptions class, which represents an address entry, and the
Address.py contains and
the Address
readAddresses()andwriteAddresses() functions, which read and write a dictionary of
Object-oriented
Address class instances
(the actualprogramming
addresses). concepts
File input/output
AddressModel.py contains
the AddressModel class, which is both a list model and a table model for
the user interface. AddressModel calls readAddresses() to read in a dictionary of Address
Python's intrinsic functions
class instances and maps the dictionary to the list and table models.
Formatting, parsing, and manipulating strings
AddressFormPane.py contains the AddressFormPane class, a user interface for editing address
entries.
Interfacing with the Java APIs and working with Java Streams
AddressMain.py contains
AddressMain
classthe
Usingthe
Python
and Java Swing
to createmain
GUIsframe. AddressMain manages the
interaction of AddressModel's components and holds an instance of JTable, an instance of
JList, and an instance
of JTabbedPane
(all of which are from javax.swing).
Working
with SQL and JDBC(TM)

Python and
JavaModular
applets
Making the Application
More
In addition, the book contains instructions for downloading and installing the Python
We've done a good job
of keeping
theJava
application
modular,
we can
do better. First,
we're going
to abstract
language
and the
Development
Kitbut
(JDK).
Terminology,
definitions,
explanations,
out the differences between
a
flat-file
model
and
a
database
model.
Then
we're
going
to
add
database
support
and numerous code samples make this book a useful learning experience.
with as few changes as possible to AddressModel.py.
Whether you are a sophisticated computer user new to programming or a serious
What we'll do is move
the file-specific
dependencies
from AddressModel
's constructor
and put will
application
developer,
Python Programming
with the Java(TM)
Class Libraries
readAddresses()
and
writeAddresses()
in
a
module
called
AddressFileU
tils.py.
All modified
give you insight into the power of Python and the know-how to put it to work.
and new files will be in a directory called AddressBook.2. Here's the original AddressModel constructor:

777

class AddressModel(AbstractTableModel, ListModel):


"""The AddressModel is both a ListModel
and a TableModel."""

Python Programming with the Java Class Libraries: A Tutorial for Building

def __init__(self):
Web and Enterprise Applications with Jython
"""Initialize
the Address model.
By
Richard Hightower
Read the dictionary from the file."""
holds
the dictionary of addresses.
Publisher:#Addison
Wesley
self.dict
=
None
Pub Date: June 28, 2002
holds the sorted list of names,
ISBN:#0-201-61616-5
Table of
#
which are keys into the dictionary.
Pages: 640
Contents
self.list = None
# byto
ListModelListeners
Characterized
easehold
of use,list
richnessof
of expression,
and concise syntax, Python has
self.listeners
=
[]
remained a premier programming language for more than a decade, and is used by
# Read the
the file.
novices and professionals
alike.addresses
In particular, itsfrom
close relationship
to Java(TM) makes
# holds
theinfile
nameideal
that
the two languages,
when used
combination,
for Web and distributed enterprise
# holds the addresses
application development.
self.fname=".\\addr.dat"
self.dict
= readAddresses(self.fname)
This tutorial
begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
# to
Store
the sorted
list of names.
help those new
programming
develop an understanding
of concepts and practical
self.list
= self.dict.keys()
techniques.
For experienced
programmers, the book demonstrates Python's breadth of
self.list.sort()
capabilities
and shows the ways that Python interfaces with Java APIs for professional
application development.

...
...

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

def writeAddresses(self):
"""Write the address data to the file."""
Fundamental programming concepts,
including statements, expressions,
writeAddresses(self.fname,
self.dict)
interpreters, and compilers

Here is the constructor as modified:


Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
...

Object-oriented programming concepts


class AddressModel(AbstractTableModel,
ListModel):
"""The AddressModel
is
both
a
ListModel
File input/output
and a TableModel."""
Python's intrinsic functions

def __init__(self):
"""Initialize
the
Formatting, parsing,
andAddress
manipulatingmodel.
strings
Read the dictionary from the file."""
Interfacing with the Java APIs and working with Java Streams

#holds the dictionary of addresses.


Using Python
Java Swing to create GUIs
self.dict
= and
None
#holds the sorted list of names,
Working with SQL and JDBC(TM)
# which are keys into the dictionary
self.list
None
Python and=Java
applets
#to
hold
list
of ListModelListeners
In addition, the
book
contains
instructions
for downloading and installing the Python
self.listeners
=
[]
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
# Read the addresses
the Address
utility.
Whether you#arefrom
a sophisticated
computer user
new to programming or a serious
self.dict
= readAddresses()
application
developer,
Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.
...
...

777

def writeAddresses(self):

"""Write
the address
dataClass
to Libraries:
the file."""
Python
Programming
with the Java
A Tutorial for Building
writeAddresses(self.dict)
Web
and Enterprise Applications with Jython
By Richard Hightower
The following are the changes we made to readAddresses() and writeAddresses(), which are
now in their own module,
AddressFileU tils.py. Notice that both functions have a default value for filename
Publisher: Addison Wesley
that they didn't have before.
Pub Date: June 28, 2002
ISBN: 0-201-61616-5
... Table of

Pages:
640
def Contents
readAddresses(filename=".\\addr.dat"):
...
Characterized by easefilename=".\\addr.dat",
of use, richness of expression, and concise
syntax, Python has
def writeAddresses(dict,
bin=0):
remained
a
premier
programming
language
for
more
than
a
decade,
and is used by
...

novices and professionals alike. In particular, its close relationship to Java(TM) makes
theistwo
when
used in combination,
ideal for Web
distributed enterprise
The result, essentially,
thatlanguages,
all file-based
functionality
has been encapsulated
outand
of AddressModel
. The
application
development.
next step is testing.
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
helpHow
those new
to programming
an understanding
of concepts and practical
Modular
Isdevelop
Modular
Enough?
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
The sad fact is that we don't have all the time in the world to tinker with our address book
application development.
application. In the real world, customers want a working product as quickly as possible, even if it's
less than perfect.
If we
strive for perfection
never Class
get it.Libraries: A Tutorial for Building Web
Python
Programming
with the we'll
Java(TM)
and Enterprise Applications with Jython covers important topics such as:
That said, I think our code at this point is modular enough.
including
expressions,
As an exercise, review the Fundamental
changes in theprogramming
address bookconcepts,
application
and thenstatements,
run the new
version. Remember that
AddressMain.py is the maininterpreters,
module, soand
to open
the application you have to type JPython AddressMain
compilers
at the system prompt. As a first step, we need to create a utility module, AddressDBUtil.py, which will
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
Allow configuration of JDBC drivers and URLs
Object-oriented programming concepts
Create the necessary tables
File input/output
Copy data from the flat file to the database
Python's intrinsic functions
Hold the readAddresses() and writeAddresses() functions
Formatting, parsing, and manipulating strings
As a second step, we have to modify AddressModel to work with AddressDBUtils.
Interfacing with the Java APIs and working with Java Streams

Working with Java Properties

Using Python and Java Swing to create GUIs

In order to configure the necessary


drivers
URLs, we have to use java.utils.Properties.
WorkingJDBC
with SQL
andand
JDBC(TM)
This class writes properties out to a text file so that a user can manually edit text with a text editor. Here's an
example.
Python and Java applets
Import the necessaryInclasses.
addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
>>> from java.util
import
Properties
and numerous
code samples
make this book a useful learning experience.

>>> from java.io import FileOutputStream, FileInputStream


Whether you are a sophisticated computer user new to programming or a serious
Create a file output stream.
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

>>> file = "addr_db.props"


>>> file = FileOutputStream(file)

777

Create an instance of Properties.

>>> props = Properties()


Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython

Set the JdbcUrl and


JdbcDriver
By Richard
Hightowerproperties.

>>> props.setProperty("JdbcUrl", "jdbc:idb=db_dev.prp")


Publisher: Addison Wesley
>>> props.setProperty("JdbcDriver", "jdbc.idbDriver")
Pub Date: June 28, 2002

0-201-61616-5
Store Table
the properties
in a fileISBN:
(addr_db.props).
of

Contents

Pages: 640

>>> props.store(file, "Database properties")


Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
#Database properties
the two languages, when used in combination, ideal for Web and distributed enterprise
#Tue Dec 28 14:46:27
PST 1999
application development.
Look at the file.

JdbcUrl=jdbc\:idb\=db_dev.prp
JdbcDriver=jdbc.idbDriver
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
Notice the file format,
which
comments (as
Pythonan
does).
The properties
are stored
name/value
help
thoseuses
new#toforprogramming
develop
understanding
of concepts
andinpractical
pairs, with each property
occupying
one
line.
This
makes
reading
the
properties
as
easy
as
writing
them.of
techniques. For experienced programmers, the book demonstrates Python's breadth
capabilities and shows the ways that Python interfaces with Java APIs for professional
Now we have to neaten up the property and file objects.
application development.

>>> file.close()
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
>>> file = None
and Enterprise Applications with Jython covers important topics such as:
>>> props = None
Notice that props has been
set to None
to show thatconcepts,
the properties
aren'tstatements,
in memoryexpressions,
anymore.
Fundamental
programming
including

interpreters, and compilers


Next we read the properties from a file. Open a file input stream.
Python basics, including operators, string formatting, namespaces, classes, errors,

>>> file = "addr_db.props"


and exceptions
>>> file = FileInputStream(file)

Object-oriented programming concepts


Create a Properties instance, and load the properties with the file input stream.
File input/output

>>> props = Properties()


>>> props.load(file)
Python's intrinsic functions
Show the values of the JdbcUrl
andparsing,
JdbcDriver
properties.
Formatting,
and manipulating
strings

>>> print props.getProperty("JdbcUrl")


Interfacing with the Java APIs and working with Java Streams
jdbc:idb=db_dev.prp
Using Python and Java Swing to create GUIs

>>> print props.getProperty("JdbcDriver")


jdbc.idbDriver Working with SQL and JDBC(TM)
Python and Java applets
Adding Property File
Support
In addition, the book contains instructions for downloading and installing the Python
Let's add a function to
AddressDBUtils.py
uses java.utils.Properties
to read explanations,
the JDBC
language
and the Java that
Development
Kit (JDK). Terminology, definitions,
properties. Let's alsoand
addnumerous
some errorcode
recovery
and
some
bullet-proof
functionality
to
check
if
the
samples make this book a useful learning experience. file exists and
to create one if not.
Whether you are a sophisticated computer user new to programming or a serious
As an exercise, try editing
the property
file Python
from AddressDBUtils.py.
try deleting
the file
and then
running
application
developer,
Programming withAlso
the Java(TM)
Class
Libraries
will
the module (don't forget
to
back
up
the
file
first).
What
happens?
give you insight into the power of Python and the know-how to put it to work.
Here's the latest version of AddressDBUtils.py:

777

from java.util import Properties


from java.io import FileOutputStream, FileInputStream, IOException, File

Python Programming with the Java Class Libraries: A Tutorial for Building

PROP_FILE = "addr_db.props"
# with
holds
the property file for the db
Web and Enterprise Applications
Jython
connection
info.
By Richard Hightower
__jdbc_url = None
# holds the JDBC URL
__jdbc_driver =Publisher:
None Addison Wesley
# holds the JDBC Driver
Pub Date: June 28, 2002

#Set some default


values.
ISBN: 0-201-61616-5
Table of
__jdbc_url="jdbc\:idb\=db_dev.prp"

Pages: 640
Contents
__jdbc_driver="jdbc.idbDriver"
Characterized by ease of use, richness of expression, and concise syntax, Python has

def __loadProps():
remained a premier programming language for more than a decade, and is used by
global
novices andPROP_FILE
professionals alike. In particular, its close relationship to Java(TM) makes
stream
= None
fileideal
input
stream
the two languages,
when used#holds
in combination,
for Web
and distributed enterprise
props
=
None
#holds
Properties
application development.
file = None
#Hold file associated
#with
theof PROP_FILE
filename.
This tutorial begins with coverage
of some
the basics of Python
programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
#See
if the file
exists.
If not
create
it.
help those new
to programming
develop
an understanding
of concepts
and practical
file
= File(PROP_FILE)
techniques.
For experienced programmers, the book demonstrates Python's breadth of
if
not file.exists():
capabilities
and shows the ways that Python interfaces with Java APIs for professional
setProps()
application development.

props
= Properties()
Python Programming
with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

#Try to load the properties.


# Create a file input stream.
Fundamental
concepts, including
expressions,
# Loadprogramming
the properties
with statements,
input stream.

try: interpreters, and compilers


try:

Python basics, including operators, string formatting, namespaces, classes, errors,


and exceptions

stream = FileInputStream(PROP_FILE)
props.load(stream)
Object-oriented
programming concepts
except IOException, e:
File input/output

Python's intrinsic
printfunctions
"Problem loading db properties file=" + PROP_FILE

print e.message
Formatting,
parsing, and manipulating strings
e.printStackTrace()
Interfacing with the Java APIs and working with Java Streams
finally:
stream.close()
Using Python and Java Swing to create GUIs

return
props
Working
with SQL and JDBC(TM)
def __storeProps(props):
Python and Java applets
global PROP_FILE
In addition,
the book
contains
instructions
for downloading
and installing the Python
file
= None
#to
hold
the file
input stream
language
the Java Development Kit (JDK). Terminology, definitions, explanations,
file
= and
FileOutputStream(PROP_FILE)
and numerous code samples make this book a useful learning experience.

# Try to create a file output stream,


Whether you
a sophisticated
computer
user new to programming or a serious
# are
and
store the
properties.
application
developer,
Python
Programming
with the Java(TM) Class Libraries will
try:
give you insight
into
the
power
of
Python
and
the know-how to put it to work.
try:

777

props.store(file, "Database properties")

except IOException, e:

print with
"Problem
db properties.
file="
Python Programming
the Javastoring
Class Libraries:
A Tutorial for Building
print
e.message
Web and Enterprise
Applications
with Jython
e.printStackTrace()
By Richard Hightower
finally:
file.close()
Publisher:
Addison Wesley
Pub Date: June 28, 2002

def getProps():
ISBN: 0-201-61616-5
Table of
global
__jdbc_url, __jdbc_driver
Pages: 640
Contents

#Load
properties
Characterized
by easethe
of use,
richness of expression, and concise syntax, Python has
props
=
__loadProps()
remained a premier programming language for more than a decade, and is used by
jdbc_url
= props.getProperty("JdbcUrl",
novices and professionals
alike. In particular, its close relationship"None")
to Java(TM) makes
jdbc_driver
props.getProperty("JdbcDriver")
the two languages, =
when
used in combination, ideal for Web and distributed enterprise
application development.

# If the prop file did not have

values
then set
some
values.
This tutorial# begins
with coverage
of some
of thedefault
basics of Python
programming. Using
if
jdbc_url
== exercises
"None":
plenty
of skill-building
and interactive programming sessions, this book will
setProps()
help those new
to programming develop an understanding of concepts and practical
else: techniques. For experienced programmers, the book demonstrates Python's breadth of
= jdbc_url
capabilities__jdbc_url
and shows the ways
that Python interfaces with Java APIs for professional
__jdbc_driver
= jdbc_driver
application development.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
def setProps():
and Enterprise
Applications with
Jython covers important topics such as:
global
__jdbc_url,
__jdbc_driver

#Create properties and then store them.


programming concepts, including statements, expressions,
propsFundamental
= Properties()
interpreters, and compilers
props.setProperty("JdbcUrl",
__jdbc_url)
props.setProperty("JdbcDriver",
__jdbc_driver)
Python basics, including operators, string formatting, namespaces, classes, errors,
__storeProps(props)
and exceptions
def getJdbcDriver():
Object-oriented programming concepts
return __jdbc_driver
File input/output

def getJdbcUrl():
Python's
intrinsic functions
return
__jdbc_url
getProps() Formatting, parsing, and manipulating strings
Interfacing with the Java APIs and working with Java Streams

Adding DDL Support

Using Python and Java Swing to create GUIs


We need DDL support in order to create the table for our address book application. To get it we first import
Working
with DriverManager
SQL and JDBC(TM) to create a connection object.
class Class to load the driver
and class
Python and
Java applets
from java.lang import
Class
from java.sql import DriverManager

In addition, the book contains instructions for downloading and installing the Python
the Javastatement,
Development
Kitis (JDK).
definitions,variable.
explanations,
Then we execute thelanguage
CREATEandTABLE
which
held in Terminology,
the create_table
and numerous code samples make this book a useful learning experience.

create_table = """
are a sophisticated
computer user new to programming or a serious
CREATE Whether
TABLEyou
Address
(
application
Python Programming
withKEY,
the Java(TM) Class Libraries will
AddrID developer, INT
PRIMARY
give
you
insight
into
the
power
of
Python
and
the
know-how
to put it to work.
Name
VARCHAR(40),
Phone
VARCHAR(15),
Email
VARCHAR(50)
)
"""

777

+ PROP_FIL

Python Programming with the Java Class Libraries: A Tutorial for Building
ThecreateTable()
method uses the create_table string to create the Address table.
Web and Enterprise Applications with Jython
By Richard Hightower

def createTable():
"""
Addison Wesley
Creates Publisher:
the Address
table.
Pub Date: June 28, 2002
"""
ISBN: 0-201-61616-5
global create_table
Table of

Pages: 640
executeUpdate(create_table)
Contents

It can't load the driver


or create theby
connection
or statement
withoutand
theconcise
assistance
of helper
methods.
Characterized
ease of use,
richness ofobject
expression,
syntax,
Python
has
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
JDBC Helper Methods
the two languages, when used in combination, ideal for Web and distributed enterprise
application
development.
Helper methods do common
things
such as execute an update, load a driver, and create connection and statement
objects. They also do error checking and cleanup. The following code illustrates some helpers. (Pay particular
This tutorial begins with coverage of some of the basics of Python programming. Using
attention to the document strings.)
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
def loadDriver():
techniques. For experienced programmers, the book demonstrates Python's breadth of
"""
capabilities
and shows
the ways
thatthe
Python
interfaces with Java APIs for professional
Loads the
driver
class
into
JVM.
Checks application
to see development.
if the class is already loaded.

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web

"""
and Enterprise Applications with Jython covers important topics such as:
global __loaded_driver
jdbc = getJdbcDriver()
try:
Fundamental programming concepts, including statements, expressions,
if not
__loaded_driver:
interpreters,
and compilers
Class.forName(jdbc)
Python
basics, including operators, string formatting, namespaces, classes, errors,
__loaded_driver=1
and exceptions
except:
error = "Unable to load the driver "+jdbc
programming concepts
printObject-oriented
error
raise DBException(error)
File input/output

def createConnection():
Python's intrinsic functions
"""
Creates a database
connection
and strings
returns it.
Formatting, parsing,
and manipulating
Loads the Database driver with loadDriver().
Interfacing with the Java APIs and working with Java Streams

returns a JDBC Connection object.


Using Python and Java Swing to create GUIs
"""
with SQL and JDBC(TM)
connection Working
= None

try:

Python and Java applets

loadDriver()
In addition, the book contains instructions for downloading and installing the Python
jdbc=getJdbcUrl()
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
connection=DriverManager.getConnection(jdbc)
and numerous code samples make this book a useful learning experience.
except Whether
Exception,
e:
you are a sophisticated
computer user new to programming or a serious
print
e.message
application developer, Python Programming with the Java(TM) Class Libraries will
error
= "Problem
creating
connection,
exception."
give you insight
into the power
of Python and
the know-how to
put it to work.
print error
raise DBException(error)

777

if connection == None:

error = "Problem
creating
connection
None"
Python Programming
with the Java
Class Libraries:
A Tutorialwas
for Building
error
Web andprint
Enterprise
Applications with Jython
DBException(error)
By Richardraise
Hightower
return connection
Publisher: Addison Wesley

def createStatement():
Pub Date: June 28, 2002
"""
ISBN: 0-201-61616-5
Table
of
Creates
a statement
object.

Pages: 640
Contents

ReturnsCharacterized
a tuple bycontaining
a JDBC
statement
ease of use, richness
of expression,
and concise syntax, Python has
and connection
object.
remained a premier programming language for more than a decade, and is used by
"""
novices and professionals alike. In particular, its close relationship to Java(TM) makes
connection
createConnection()
the two =languages,
when used in combination, ideal for Web and distributed enterprise
return application
connection.createStatement(),
connection
development.
def executeUpdate(str):
This tutorial begins with coverage of some of the basics of Python programming. Using
"""
plenty of skill-building exercises and interactive programming sessions, this book will
Executes
statement.
helpan
thoseupdate
new to programming
develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of

Returnscapabilities
the number
oftherows
involved.
and shows
ways that
Python interfaces with Java APIs for professional
"""
application development.
statement, connection = None, None
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
num_rows=-1
try: and Enterprise Applications with Jython covers important topics such as:
try:
statement,connection=createStatement()
Fundamental
programming
concepts, including statements, expressions,
num_rows
= statement.executeUpdate(str)
interpreters, and compilers

except
Exception, e:
Python basics, including operators, string formatting, namespaces, classes, errors,
e.printStackTrace()
and exceptions
print e.message
print "Problem
executing
update\n"+str
Object-oriented
programming
concepts
finally: File input/output
if(connection):connection.close()
Python's intrinsic functions

return num_rows
Formatting, parsing, and manipulating strings
Notice all of the error checking and recovery going on. Since we plan to execute more statements, it's good to
with the Java APIs and working with Java Streams
have all such tasks handledInterfacing
in one place.
Using Python and Java Swing to create GUIs

Creating the Address Table

Working with SQL and JDBC(TM)


All the preliminaries are out of the way, leaving only the execution of the CREATETABLE statement. This is
Python
applets
going to be easy. All it takes
is oneand
callJava
to executeUpdate()
.
In addition, the book contains instructions for downloading and installing the Python
def createTable():
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
"""
numerous
code samples
make this book a useful learning experience.
Createsandthe
Address
table.
"""
you are a sophisticated computer user new to programming or a serious
global Whether
create_table
application
developer, Python Programming with the Java(TM) Class Libraries will
executeUpdate(create_table)

give you insight into the power of Python and the know-how to put it to work.
We want to run createTable() from the command line, so we need to add command-line parameter
parsing in the main block ( if__name__=="__main__ "block), which checks to see if "c" is passed to
the command line and, if so, creates the table. (Passing "p" creates the properties file.)

777

if __name__ ==
"__main__":
Python
Programming with the Java Class Libraries: A Tutorial for Building
from sys
argvApplications with Jython
Webimport
and Enterprise
By Richard Hightower

#Process the command line arguments.


for arg in
argv:
Publisher:
Addison Wesley
if Pub
arg
==
"c":
Date: June
28, 2002
getProps()
ISBN: 0-201-61616-5
Table of
str = "Creating the table using "
Pages: 640
Contents
str = str+getJdbcDriver()+" at "+ getJdbcUrl()
print
str
Characterized
by ease
of use, richness of expression, and concise syntax, Python has
createTable()
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes

if
arglanguages,
== "p":
the two
when used in combination, ideal for Web and distributed enterprise
print
"Creating the properties file: "+PROP_FILE
application
development.
getProps()
print
This tutorial
beginsgetJdbcDriver()
with coverage of some of the basics of Python programming. Using
getJdbcUrl()
plenty of print
skill-building
exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
Now we have our AddressDBUtils.py
module. Here's
how to create
it in DOS:
techniques. For experienced
programmers,
the book
demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.

C:\JPython_book\scripts\chap17\AddressBook3>JPython AddressDBUtils.py c
Try creating the Address table yourself as an exercise.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

Inserting Address Records into the Address Table

Fundamental
programming
concepts,
including
To get addresses into the database,
we have
to transform
an instance
of the statements,
Addressexpressions,
class into a record.
andentries.
compilers
Define the format string forinterpreters,
the insert
PythonName,
basics, including
string formatting, namespaces, classes, errors,
params = """AddrID,
Phone,operators,
Email"""
and
exceptions
insert = """
Object-oriented programming concepts

INSERT INTO
Address
File input/output
(""" + params + """)
Python's intrinsic functions

VALUES
(%s)Formatting, parsing, and manipulating strings
"""
Interfacing with the Java APIs and working with Java Streams
Define functions to create an INSERT statement.
Using Python and Java Swing to create GUIs

def insertAddress(address, statement=None):


Working with SQL and JDBC(TM)
"""
Inserts the AddrID, Name, Phone,
and Java applets
Email intoPython
a row.
"""
In addition, the book contains instructions for downloading and installing the Python
id = getID()
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
a = address
and numerous code samples make this book a useful learning experience.
tup = (
str(id),
Whether
you are a sophisticated computer user new to programming or a serious
formatSQLStr(a.name()),
application
developer, Python Programming with the Java(TM) Class Libraries will
formatSQLStr(a.phoneNumber()),
give
you insight into the power of Python and the know-how to put it to work.
formatSQLStr(a.email())
)
values = join(tup, ",")
if statement:

777

executeUpdate(insert
% values,
statement)
Python
Programming with the Java
Class Libraries:
A Tutorial for Building
else: Web and Enterprise Applications with Jython
print
insert % values
By
Richard Hightower
Invoke the helper function
formatSQLStr() to transform the address information into a string that SQL
Publisher: Addison Wesley
understands.
Pub Date: June 28, 2002
ISBN: 0-201-61616-5
def Table
formatSQLStr(str):
of

Pages:
640
"""Formats a string
into a SQL string"""
Contents
str = "'%s'" % str
by ease of use, richness of expression, and concise syntax, Python has
returnCharacterized
str

remained a premier programming language for more than a decade, and is used by
and professionals
alike.
In particular,
its close
relationship
Java(TM)
makes
Now we'll add all ofnovices
our address
book data to the
database
(users like
you to
do this for to
them).
For this
we need
the
two
languages,
when
used
in
combination,
ideal
for
Web
and
distributed
enterprise
theloadFromFile() function, which reads the address.dat file and stores a given address in the Address
application development.
table.
This tutorial begins with coverage of some of the basics of Python programming. Using
def loadFromFile():
""" plenty of skill-building exercises and interactive programming sessions, this book will
new to
programming
develop an understanding
of concepts and practical
Loads help
thethose
flat
file
of addresses
into
techniques.
For
experienced
programmers,
the
book
demonstrates
Python's breadth of
the Address table.
capabilities
and
shows
the
ways
that
Python
interfaces
with
Java
APIs
for professional
"""
application development. import readAddresses
from AddressFileUtils
dict = readAddresses()
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and
with Jython
topics such as:
# Enterprise
Create Applications
a statement
for covers
the important
database.

# Add all of the addresses to the table.


try:

Fundamental programming concepts, including statements, expressions,

statement,
connection
= createStatement()
interpreters, and
compilers

# Iterate
through
collection
Python basics,
includingthe
operators,
string formatting, namespaces, classes, errors,
# ofandaddresses.
Add each address to the
exceptions
# database.
Object-oriented
programming concepts
for address
in dict.values():
insertAddress(address, statement)
File input/output

finally:
Python's intrinsic functions
connection.close()
parsing,
andblock
manipulating
Next we add the followingFormatting,
statements to
the main
so we canstrings
read loadFromFile() from the
command line.
Interfacing with the Java APIs and working with Java Streams

if __name__ == "__main__":
Using Python and Java Swing to create GUIs
from sys import argv
Working with SQL and JDBC(TM)

#Process the command line arguments.


for Python
arg and
in Java
argv:
applets
...
...

In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and
samples make this book a useful learning experience.
ifnumerous
arg ==code
"l":

loadFromFile()
Whether you are a sophisticated computer user new to programming or a serious
application
developer,
Python Programming
the Java(TM)
Class
willHere's
To load the data from
the file, we
run AddressDBUtils.py
from thewith
command
line with
the Libraries
"1" option.
the DOS prompt: give you insight into the power of Python and the know-how to put it to work.

C:\JPython_book\scripts\chap17\AddressBook3>JPython AddressDBUtils.py l

777

Reading Addresses from the Address Table

Python Programming with the Java Class Libraries: A Tutorial for Building

Now we need to implement


theEnterprise
readAddresses()
and writeAddresses()
functions.
Web and
Applications with
Jython
readAddresses()
is
easywe
just
select
all
of
the
records
and
put
them
in
a
dictionary.
By Richard Hightower
writeAddresses() is more difficult. What if someone removes an address from the dictionaryhow will
we know without changing
AddressModel
? We'll skip writing addresses for now and instead integrate
Publisher:
Addison Wesley
AddressDBUtils.py intoPub
the Date:
application.
June 28, 2002
ISBN: 0-201-61616-5
Here'sTable
the code
of for readAddresses() and writeAddresses():

Contents

Pages: 640

def readAddresses():
""" Characterized by ease of use, richness of expression, and concise syntax, Python has
remained
a premierdata
programming language for more than a decade, and is used by
Read the
Address
novices
and
professionals
alike. In particular,
AddrID, Name, Phone,
Email its close relationship to Java(TM) makes
the
two
languages,
when
used
in
combination,
ideal for Web and distributed enterprise
returns a dictionary full of addresses
application
development.
"""
dict = None

This tutorial begins with coverage of some of the basics of Python programming. Using
try: plenty of skill-building exercises and interactive programming sessions, this book will
help
those new to programming
develop
understanding of concepts and practical
statement,
connection
= ancreateStatement()
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities
dict =and
{}shows the ways that Python interfaces with Java APIs for professional
application
development.
results
= statement.executeQuery(select_all)
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
while results.next():
and Enterprise Applications with Jython covers important topics such as:

id = results.getString("AddrID")
name = results.getString("Name")
phoneprogramming
= results.getString("Phone")
Fundamental
concepts, including statements, expressions,
email
=
results.getString("Email")
interpreters, and compilers
dict[name]=Address(name, phone, email)

Python basics, including operators, string formatting, namespaces, classes, errors,


finally: and exceptions

connection.close()
Object-oriented programming concepts

return dict

File input/output

def writeAddresses(dict):
Python's intrinsic functions
pass
Formatting, parsing, and manipulating strings
As you probably noticed, writeAddresses() isn't doing anything yet.
Interfacing with the Java APIs and working with Java Streams

Integrating AddressModel with the Database

Using Python and Java Swing to create GUIs

Instead of replacing the flatWorking


file, let'swith
see how
polymorphically
SQLtoand
JDBC(TM) add the database as an option. Via the
__import__ function, AddressModel imports functions from AddressIO that dynamically load the
I/O utility module (AddressBook3\
AddressIO.py).
Python and
Java applets

from java.util
import
Properties
In addition,
the book
contains instructions for downloading and installing the Python
from java.io language
importandFileInputStream,
IOException
the Java Development Kit FileOutputStream,
(JDK). Terminology, definitions,
explanations,
and numerous code samples make this book a useful learning experience.

#holds property file for the db connection info.


PROP_FILE = "addr.props"
Whether you are a sophisticated computer user new to programming or a serious
def readAddresses():
application developer, Python Programming with the Java(TM) Class Libraries will
pass give you insight into the power of Python and the know-how to put it to work.
def writeAddresses(dict):
pass
...
...

777

Python Programming with the Java Class Libraries: A Tutorial for Building
def getModuleName():
Web and Enterprise Applications with Jython
#Load the properties.
Hightower
props By
=Richard
__loadProps()
return props.getProperty("module_name", "AddressDBUtils")
Publisher: Addison Wesley
...
Pub Date: June 28, 2002
...
ISBN: 0-201-61616-5
module
=
__import__(getModuleName())
Table of

Pages:
640
readAddresses
= module.readAddresses
Contents
writeAddresses = module.writeAddresses

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained
programming
for more than a decade, and is used by
To switch back to the
flat file, aallpremier
we have
to do is edit language
addr.props.
novices and professionals alike. In particular, its close relationship to Java(TM) makes
#Database properties
the two languages, when used in combination, ideal for Web and distributed enterprise
#Wed Dec 29 20:24:54
PST 1999
application development.

#module_name=AddressDBUtils
module_name=AddressFileUtils
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
As an exercise, run the
modes, switching
and forth between
them. and practical
helpapplication
those newintoboth
programming
develop back
an understanding
of concepts
techniques. For experienced programmers, the book demonstrates Python's breadth of
A Database-Aware
Dictionary
capabilities
and shows the ways that Python interfaces with Java APIs for professional
application development.
How do we know which addresses need to be written out of the database? One way is to set a dirty flag, which
withhas
thechanged.
Java(TM)But
Class
Libraries:
A Tutorial
for Building Web
will tell us when onePython
of the Programming
instance variables
what
about adding
new addresseshow
much
and
Enterprise
Applications
with
Jython
covers
important
topics
such
as:
code will we have to modify?
In fact, we can add the functionality that will answer these questions without changing AddressModel or
Fundamental
programming
concepts,
including
expressions,
any of the GUI. All we need
to do is define
a database-aware
dictionary
thatstatements,
replaces the
dictionary that
interpreters,
AddressModel is presently
using. and compilers

operators,
string
formatting,
namespaces,
classes,
Recall the dictionary class Python
that we basics,
createdincluding
in Chapter
6. We can
use what
we learned
from it to
create errors,
a
and
exceptions
dictionary class that adds and removes rows in the Address table. We'll call it AddressDBDict and put it in
theAddressBook4.py module.
Object-oriented programming concepts

class AddressDBDict:
File input/output
...
...
Python's intrinsic functions
def __setitem__(self,
value):strings
Formatting, parsing,key,
and manipulating
statement, connection = createStatement()
try:Interfacing with the Java APIs and working with Java Streams
addr = AddressDB()
Using addr.fromAddress(value,
Python and Java Swing to create GUIs statement)
self.dict[key]=addr
Working with SQL and JDBC(TM)
finally:
connection.close()
Python and Java applets
def __delitem__(self,
key):
In addition, the book contains
instructions for downloading and installing the Python
statement,
connection
= createStatement()
language and the Java Development Kit
(JDK). Terminology, definitions, explanations,
try:
and numerous code samples make this book a useful learning experience.
addr = self.dict[key]
Whether youaddr.remove(statement)
are a sophisticated computer user new to programming or a serious
del(self.dict[key])
application developer,
Python Programming with the Java(TM) Class Libraries will
finally:
give
you insight into the power of Python and the know-how to put it to work.
connection.close()

777

As you can see, the "overridden" __setitem__ and __delitem__ methods create a JDBC statement
object and interact with AddressDBDict.

__setitem__ takes
a regular
addresswith
instance
as an argument
to create an
instance for
of Building
Python
Programming
the Java
Class Libraries:
A Tutorial
AddressDBDictWeb
. It then
the fromAddress()
method,
andcalls
Enterprise
Applications with
Jythonpassing it a JDBC statement object.
Hightower
fromAddress()ByisRichard
where the
Address record is inserted into the Address table.
__delitem__ calls Publisher:
the AddressDBDict
Addison Wesleyinstance it retrieves from AddressModel and invokes its
remove() method, passing
it
a
JDBC28,
statement
object. remove() deletes the Address record from the
Pub Date: June
2002
Address table.

ISBN: 0-201-61616-5

Table of
Contents

Pages: 640

Characterized by ease of use, richness of expression, and concise syntax, Python has
How Many
Connections Are Opened and Closed?
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
It may look like
closes a connection
everyand
time
it adds orenterprise
deletes
theAddressDBDict
two languages, whencreates
used inand
combination,
ideal for Web
distributed
a record, but that
would be
awfully expensive as well as inefficient. Actually, only one connection
application
development.
to the database is created. Take a look at the createStatement() function and the
Connect class
the AddressBook4.py
module
see how
is done.
Thisintutorial
begins with coverage
oftosome
of thethis
basics
of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help
those new
to programming
develop an understanding of concepts and practical
A Database-Aware
Address
Class:
AddressDB
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
AddressDB is a subclass of Address, which notifies it, via the markDirty() method, when its
application development.
member variables change. Address defines markDirty() and calls it in its constructor. AddressDB
overridesmarkDirty()
and adds the ability
to update
the corresponding
record
in the for
Address
tableWeb
when
Python Programming
with the
Java(TM)
Class Libraries:
A Tutorial
Building
changes are made. and Enterprise Applications with Jython covers important topics such as:
Recall that the Address class has no setter methods for its variables but sets them through __init__ . The
first time __init__ is called,
the dirtyprogramming
flag is set to concepts,
0 (false); including
at all subsequent
calls,expressions,
it's set to 1 (true).
Fundamental
statements,
interpreters, and compilers
Here's some of the code for Address and AddressDB showing the interaction between markDirty(),
dirty, and isDirty()
:
Python
basics, including operators, string formatting, namespaces, classes, errors,
and exceptions

class Address:

Object-oriented programming concepts

...
__dirty File
= input/output
-1
Python's intrinsic
functions phone_number="", email="",
def __init__(self,
name="",
...
Formatting,
parsing, and manipulating strings
...
self.markDirty()
Interfacing with the Java APIs and working with Java Streams
...
...
Using Python and Java Swing to create GUIs
def markDirty(self):
... Working with SQL and JDBC(TM)
self.__dirty = self.__dirty + 1
Python and Java applets

def isDirty(self):
In...
addition, the book contains instructions for downloading and installing the Python
language
the Java Development Kit (JDK). Terminology, definitions, explanations,
returnandself.__dirty
and numerous code samples make this book a useful learning experience.

class AddressDB(Address):
Whether you are a sophisticated computer user new to programming or a serious
...
application developer, Python Programming with the Java(TM) Class Libraries will
...
give you insight into the power of Python and the know-how to put it to work.

def markDirty(self):
...
Address.markDirty(self)
if(self.isDirty()):

777

address

def

self.__update()
Python Programming
with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
__update(self):
By Richard Hightower
...
statement,
connection
= createStatement()
Publisher: Addison
Wesley
Pub Date: June 28, 2002

Table of
Contents

try:ISBN: 0-201-61616-5
self.update(statement)
Pages: 640
finally:
connection.close()
Characterized
by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by

markDirty() calls the Address of the class; then it calls its isDirty() method to determine if the
novices and professionals alike. In particular, its close relationship to Java(TM) makes
data is dirty. If so, AddressDB's __update() method is called by its markDirty() method in order to
the two languages, when used in combination, ideal for Web and distributed enterprise
create a JDBC statement object and to update the record in the database.
application development.

In this way the base class and the subclass interact to determine the state of the address instance. If the data is
This tutorial begins with coverage of some of the basics of Python programming. Using
dirty, it's written out to the database and made clean again.
plenty of skill-building exercises and interactive programming sessions, this book will
help those
newupdates
to programming
an understanding
concepts
and practical
AddressDB'supdate()
method
the record;develop
its remove()
methodof
deletes
the record;
and its
techniques.
For
experienced
programmers,
the
book
demonstrates
Python's
fromAddress() method inserts a new one. The following code shows how these methods breadth
work: of
capabilities and shows the ways that Python interfaces with Java APIs for professional
where = """ application development.

WHERE
"""

Python
Programming
with the Java(TM) Class Libraries: A Tutorial for Building Web
AddrID
= %(_AddressDB__id)s
and Enterprise Applications with Jython covers important topics such as:

select = """
UPDATE

Fundamental programming concepts, including statements, expressions,


interpreters, and compilers

Address
SET

Python basics, including operators, string formatting, namespaces, classes, errors,

Nameand=exceptions
'%(_Address__name)s',
Phone = '%(_Address__phone_number)s',
Object-oriented
programming concepts
Email
= '%(_Address__email)s'
""" + where
File input/output
delete = """
DELETE FROM
Python's intrinsic functions
Address
""" + where
Formatting, parsing, and manipulating strings
insert = """
Interfacing with the Java APIs and working with Java Streams

INSERT INTO
Address
Using Python and Java Swing to create GUIs
(AddrID, Name, Phone, Email)
Working with SQL and JDBC(TM)

VALUES
( Python and Java applets
%(_AddressDB__id)s,
In addition, the book contains instructions for downloading and installing the Python
'%(_Address__name)s',
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
'%(_Address__phone_number)s',
and numerous code samples make this book a useful learning experience.
'%(_Address__email)s'
)
Whether
you are a sophisticated computer user new to programming or a serious
""" application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

class AddressDB(Address):
...
...
def update(self, statement=None):

777

... Programming with the Java Class Libraries: A Tutorial for Building
Python
if(statement):
Web
and Enterprise Applications with Jython
...
By Richard Hightower
statement.executeUpdate(select % self.__dict__)
= 0

Publisher:self.__dict__["_Address__dirty"]
Addison Wesley

...

...

Pub Date: June 28, 2002


Table def
of
Contents

ISBN: 0-201-61616-5

remove(self,
statement=None):
Pages: 640
...
if(statement):
Characterized
by ease of use, richness of expression, and concise syntax, Python has
statement.executeUpdate(delete
% self.__dict__)
remained a premier
programming language for more than a decade,
and is used by

novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
def fromAddress(self,
application development. addr, statement=None):

# Copy the address.


name =This
addr.name()
tutorial begins with coverage of some of the basics of Python programming. Using
phone_number=addr.phoneNumber()
plenty of skill-building exercises and interactive programming sessions, this book will
email=addr.email()
help those new to programming develop an understanding of concepts and practical
self.__dict__["_Address__dirty"]
-1 demonstrates Python's breadth of
techniques. For experienced programmers, the=book
Address.__init__(self,name,
phone_number,
email,
address_lines=None)
capabilities and shows the ways that Python
interfaces with Java
APIs for
professional
application development.

# Insert the record into the database.


Python Programming
self.__id
= getID()with the Java(TM) Class Libraries: A Tutorial for Building Web
Enterprise
with Jython covers important topics such as:
str = and
insert
% Applications
self.__dict__
if statement:
statement.executeUpdate(str)
Fundamental programming concepts, including statements, expressions,
...
interpreters, and compilers

AddressDB knows how to deal with the database, and, since it has the same interface as Address, the GUI
Python
basics,knowing
includingwhich
operators,
string
formatting, namespaces,
classes,how
errors,
knows how to work with either
without
is which.
AddressDBDict
, too, knows
to deal
and exceptions
with the database. What's more, it has the same interface as a Python dictionary object, which means that, like a
dictionary object, it can work with AddressModel,AddressMain,AddressFormPane, and so
Object-oriented programming concepts
forth, without these classes having to be changed. This is polymorphism at its deceptive best.
File input/output
To make the deception complete, AddressDBUtil'sreadAddresses() function has to get in on the
action. Instead of a dictionary
full ofintrinsic
addressfunctions
instances, it now has to return AddressDBDict, which holds
Python's
AddressDB instances. Here's its code (from AddressBook4\AddressDBUtils.py) with the interesting parts
highlighted in bold:
Formatting, parsing, and manipulating strings

def readAddresses():
Interfacing with the Java APIs and working with Java Streams
...
Using Python and Java Swing to create GUIs
...
try:
Working withconnection
SQL and JDBC(TM)
statement,
= createStatement()
...
Python and Java applets

dict = AddressDBDict()

In addition, the book contains instructions for downloading and installing the Python
results
= Java
statement.executeQuery(select_all)
language
and the
Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.

while results.next():
idare=a sophisticated
results.getString("AddrID")
Whether you
computer user new to programming or a serious
name
= results.getString("Name")
application developer,
Python Programming with the Java(TM) Class Libraries will
phone
give you insight
into =
theresults.getString("Phone")
power of Python and the know-how to put it to work.
email = results.getString("Email")
addr=AddressDB(name, phone, email)
dict.dict[name] = addr
addr.setID(id)

777

finally:
Python Programming with the Java Class Libraries: A Tutorial for Building
#connection.close()
Web
and Enterprise Applications with Jython
pass
By
Richard Hightower
return dict
Publisher: Addison Wesley
Pub Date: June 28, 2002
Using the Database-Supported
Address Book Application

Now

Table of
our
address book
Contents

ISBN: 0-201-61616-5
Pages: 640
application
has

database support. To get that support, and to keep the application


backward-compatible with the flat-file format, we tapped into the power of Python and polymorphism. Try these
Characterized by ease of use, richness of expression, and concise syntax, Python has
exercises:
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
Deploy the address
book
application
in used
a different
database than
you've
using.enterprise
the two
languages,
when
in combination,
idealtheforone
Web
and been
distributed
application development.
Add the ability to track a phone conversationthat is, take notes while you're talkingand pull up a list
of notes for a given
addressbegins
entry. with
To accomplish
you'll
a database
tableprogramming.
called Phone Log
with a
This tutorial
coverage ofthis
some
of need
the basics
of Python
Using
notes field, anplenty
identity
and a foreign
key field
that references
AddrIDsessions,
in the Address
table.
You'll
offield,
skill-building
exercises
and interactive
programming
this book
will
also need GUIhelp
components
edit, and delete
notes.
those newtotoview,
programming
develop
an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
Make it possible
to travel with
the address
book
application,
workingwith
withJava
a laptop
database server.
capabilities
and shows
the ways
that
Python interfaces
APIsand
for aprofessional
application development.
Add the ability to copy Address records from a database format to a flat-file format.

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
Add a dialog box that allows a user to copy data to the flat-file format and work with the application in
and Enterprise Applications with Jython covers important topics such as:
mobile modethat is, a mode that reads from the flat file instead of from the database server.
Enable the user to reconnect
to theprogramming
database. concepts, including statements, expressions,
Fundamental

interpreters, and compilers

Summary

Python basics, including operators, string formatting, namespaces, classes, errors,


and exceptions
In this chapter we covered SQL/JDBC programming. We used what we learned to provide database support for
our address book application.
We took a brief
tour of SQL
fundamentals, including the SQL sublanguages, DDL
Object-oriented
programming
concepts
and DML.
File input/output
The exercises showed how to connect and use two different databases: a JDBCODBC bridge (Microsoft
Access) and a pure JDBC connection
(InstantDB).
We saw some of the difficulties in porting to and running on
Python's intrinsic
functions
multiple databases.
Formatting, parsing, and manipulating strings
We also saw the importance of modular design when we grafted database support onto the address book
application. In addition, weInterfacing
used java.Utils.Properties
to make
changing
properties easier. We also
with the Java APIs and working
with Java
Streams
discovered the dynamic capabilities of Python's __import__ statement, which uses the module name in a
Swing to
property file to load an I/OUsing
utility Python
module.and
TheJava
dynamism
ofcreate
PythonGUIs
and polymorphism was reinforced when we
added database support to the AddressModel class by creating a database-aware subclass and a databaseWorking with SQL and JDBC(TM)
aware dictionary.
Python and Java applets

CONTENTS
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
CONTENTS
Web and Enterprise Applications with Jython
By Richard Hightower

Chapter 18. Applets


Publisher: Addison Wesley
Pub Date: June 28, 2002

What Are Applets?


ISBN: 0-201-61616-5
Table of
Working with Applets
Pages: 640
Contents
Using an Applet as a Container
Characterized
by ease
of Application
use, richness ofinto
expression,
and concise syntax, Python has
Transforming
the Address
Book
an Applet
remained a premier programming language for more than a decade, and is used by
Advanced Topic: AppletContext and AppletStub
novices and professionals alike. In particular, its close relationship to Java(TM) makes
Summary the two languages, when used in combination, ideal for Web and distributed enterprise

application development.
Terms in This Chapter
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty
programming
Appletof skill-building exercises and interactive
HTTP/FTP
protocolsessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques.
the bookfile
demonstrates Python's breadth of
Batch file For experienced programmers,JAR/zip
capabilities and shows the ways that Python interfaces with Java APIs for professional
Browser development.
Lifecycle management
application
BrowserProgramming
simulator with the Java(TM) Class
Sandbox
Python
Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
Code base
Stub
Context
Fundamental programming concepts,Tag
including statements, expressions,
interpreters, and compilers
Once upon a time, there was a relatively new company named Netscape that became king of the Internet. It was
Netscape's acceptance of Java
applets
thatincluding
put Java on
the map.string formatting, namespaces, classes, errors,
Python
basics,
operators,
and exceptions
If you follow Java, you know that, ironically, it's had a lot more impact on the server side (J2EE, servlets, JMS,
RMI, JAVA IDL, EJB, etc.)
than on the client
side (applets,
Swing). However, change is under way. With later
Object-oriented
programming
concepts
Java releases, Sun Microsystems has introduced a plug-in for browsers that addresses many of the shortcomings
input/output
of applets by allowing themFile
to be
cached.

Python's intrinsic functions

What Are Applets?

Formatting, parsing, and manipulating strings


Applets represent a way to deliver safe code for producing lively Internet GUIs. They execute within a browser
Interfacing
Java APIs
andsoworking
with
Streams
and are associated with (i.e.,
embeddedwith
in) the
an HTML
page,
they must
be Java
inherently
portable to run in a
variety of browsers on a variety of platforms.
Using Python and Java Swing to create GUIs
Let's rewind a bit. Applets execute within a browser, which means that code that somebody else wrote is running
Working with SQL and JDBC(TM)
on your computer. That may sound dangerous, but applets can run only inside a security "sandbox," which won't
allow them to do things like
read or
write
files, read environment variables, or open network connections to
Python
and
Javatoapplets
any host except the one on which they originated. With current releases of Java, you can tweak the sandbox to
give applets more privileges,
butthe
they'll
never
be allowed
to do for
anything
that would
you. What's
more,
In addition,
book
contains
instructions
downloading
andharm
installing
the Python
they're virus-resistant.
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
All applets derive from java.applet.Applet, and so, since Jython compiles to Java bytecode and can
subclass a Java class,Whether
all we have
is subclass java.applet.Applet
and compile.
Sounds easy
you to
aredo
a sophisticated
computer user new to programming
or a serious
enough, doesn't it? Inapplication
fact, if you've
workedPython
with applets,
most of with
this chapter
will beClass
a review,
exceptwill
for
developer,
Programming
the Java(TM)
Libraries
compiling Jython code
an applet.
givetoyou
insight into the power of Python and the know-how to put it to work.

Working with Applets

777

Let's start off with anPython


interactive
session. Import
from
the java.applet
package.
Programming
withApplet
the Java
Class
Libraries: A
Tutorial for Building
Web and Enterprise Applications with Jython

>>> from java.applet


import Applet
By Richard Hightower
>>> applet = Applet()
Publisher: Addison Wesley

An applet is a panel (java.awt.Panel), and, as we learned earlier, a panel is also a component.


Pub Date: June 28, 2002

ISBN: 0-201-61616-5
>>> Table
applet.class.superclass
of

Pages:
640at -731859681>
<jclass
java.awt.Panel
Contents

Characterized
by ease
of use, richness
of expression,
and concise(and
syntax,
has
So, if an applet is a panel,
and a panel
is a component,
an applet
is also a component
thusPython
a component
remained
a premieryou've
programming
language
for moreand
thanpanels
a decade,
andtois applets
used byas well.
container). That means
that everything
learned about
components
applies
novices and professionals alike. In particular, its close relationship to Java(TM) makes
two languages,
when used in combination, ideal for Web and distributed enterprise
Surveying thethe
Applet
Landscape
application development.

Applet inherits allThis


of class java.applet.Applet's functionality. What's more, the Applet class
tutorial begins with coverage of some of the basics of Python programming. Using

employs the Faade plenty


design of
pattern,
which facilitates
of many programming
utilities in java.net,
java.io,
forth, so
skill-building
exercisesthe
anduse
interactive
sessions,
this and
booksowill
it makes tasks such as
Web
image
downloading
as
easy
as
possible.
help those new to programming develop an understanding of concepts and practical

Forapplets
experienced
programmers,
book demonstrates
To see the amount oftechniques.
functionality
provide,
take a look atthe
Applet
's methods. Python's
Here are breadth
just the of
first
capabilities and shows the ways that Python interfaces with Java APIs for professional
fifteen:
application development.

>>> for i in range (0, 15):


Python
Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
...
print
methods[i]
and
Enterprise
Applications with Jython covers important topics such as:
...
public void java.applet.Applet.destroy()
public java.applet.AppletContext
Fundamental programming java.applet.Applet.getAppletContext()
concepts, including statements, expressions,
public java.lang.String
java.applet.Applet.getAppletInfo()
interpreters, and compilers
public java.applet.AudioClip java.applet.Applet.getAudioClip(java.net.URL)
public java.applet.AudioClip
java.applet.Applet.getAudioClip(java.net.URL,jav
Python basics, including
operators, string formatting, namespaces, classes, errors,
public java.net.URL
java.applet.Applet.getCodeBase()
and exceptions
public java.net.URL java.applet.Applet.getDocumentBase()
Object-oriented
programming concepts
public java.awt.Image
java.applet.Applet.getImage(java.net.URL)
public java.awt.Image java.applet.Applet.getImage(java.net.URL,java.lang.Stri
File input/output
public java.util.Locale
java.applet.Applet.getLocale()
public java.lang.String java.applet.Applet.getParameter(java.lang.String)
Python's intrinsic functions
public java.lang.String[][] java.applet.Applet.getParameterInfo()
public void java.applet.Applet.init()
Formatting, parsing, and manipulating strings
public boolean java.applet.Applet.isActive()
public static final
java.applet.AudioClip
Interfacing
with the Java APIs and working with Java Streams
java.applet.Applet.newAudioClip(java.net.URL)
Using Python and Java Swing to create GUIs
Here are the rest:

Working with SQL and JDBC(TM)

>>> for i in range (15, 23):


...
print methods[i]
Python and Java applets
...
In addition, the book contains instructions for downloading and installing the Python
public void java.applet.Applet.play(java.net.URL)
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
public void java.applet.Applet.play(java.net.URL,java.lang.String)
and numerous code samples make this book a useful learning experience.
public void java.applet.Applet.resize(int,int)
public void java.applet.Applet.resize(java.awt.Dimension)
are a sophisticated computer user new to programming or a serious
public final Whether
void you
java.applet.Applet.setStub(java.applet.AppletStub)
application
developer,
Python Programming with the Java(TM) Class Libraries will
public void java.applet.Applet.showStatus(java.lang.String)
give
you
insight
into
the
power of Python and the know-how to put it to work.
public void java.applet.Applet.start()
public void java.applet.Applet.stop()

777

That's a lot of methods to learn, and this is just the tip of the iceberg since we're not considering any methods that
Applet inherits from its superclasses. (We covered those methods earlier in this book.)

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and
Enterprise
Applications with Jython
Using an Applet
as
a Container
By Richard Hightower

Because you can use applets interchangeably with panels they're easy to test and debug. Debugging is even easier
Publisher:application
Addison Wesley
if the applet runs as a standalone
rather than within a browser. Let's run one from the interactive
Pub Date: June 28, 2002
interpreter.
ISBN: 0-201-61616-5

Table of
Import
Frame
Applet,List, and
Pages:
640.
Contents

>>> from java.applet


Applet
Characterized import
by ease of use,
richness of expression, and concise syntax, Python has
>>> from java.awt
List, Frame
remainedimport
a premier programming
language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
Create an instance of Applet and List; add the List instance to the applet instance.
the two languages, when used in combination, ideal for Web and distributed enterprise
development.
>>> applet = application
Applet()

>>> list = List()


This tutorial begins with coverage of some of the basics of Python programming. Using
>>> applet.add(list)
plenty of skill-building exercises and interactive programming sessions, this book will
java.awt.List[list0,0,0,0x0,invalid,selected=null]
help those new to programming develop an understanding of concepts and practical
Forapplet
experienced
Create an instance oftechniques.
Frame; add
to it.programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
>>> frame = Frame("Frame
that contains the Applet")

>>> frame.add(applet)
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
java.applet.Applet[panel0,0,0,0x0,invalid,layout=java.awt.FlowLayout]
and Enterprise Applications with Jython covers important topics such as:
Pack and show frame.

>>> frame.pack() Fundamental programming concepts, including statements, expressions,


interpreters, and compilers
>>> frame.visible=1
Add some items to list. Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions

>>> list.add("Hello")
Object-oriented programming concepts
>>> list.add("Goodbye")
File input/output
Figure 18-1 shows our first applet. (It may be a stretch to call it an applet since we're using it like a panel.) You
can see that working with an
appletintrinsic
is much functions
like working with a panel, except that there's a lot more to it.
Python's
Figure
18-1.and
Ourmanipulating
First So-Called
Formatting,
parsing,
stringsApplet

Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs
Working with SQL and JDBC(TM)
Python and Java applets
In addition,
the book contains instructions for downloading and installing the Python
Applet Lifecycle
Management

language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
The browser lets applets know when they're no longer active or in view. It also tells them when they're created
and when they're about
to be destroyed
they can create
or free
resources.
Such notification
called lifecycle
Whether
you are a so
sophisticated
computer
user
new to programming
or a is
serious
management. An applet
is
created
and
executes
within
a
browser.
The
browser
determines
when
resources
application developer, Python Programming with the Java(TM) Class Libraries
will
should be created or give
restored
and
notifies
the
applet
accordingly.
you insight into the power of Python and the know-how to put it to work.
Here are the browser's methods for notifying an applet of a lifecycle event:

777

init() creates the applet

Programming
destroy()Python
destroys
the applet with the Java Class Libraries: A Tutorial for Building

start()

Web and Enterprise Applications with Jython


By Richard
Hightower
makes
the applet
visible or active

stop() makesPublisher:
the appletAddison
invisible
or inactive
Wesley
Pub Date: June 28, 2002

To implement these methods,


we have
to subclass the Applet class.
ISBN:
0-201-61616-5

Table of

Pages: 640

ImportContents
the Applet class and the needed java.awt classes.

Characterized import
by ease of use,
richness of expression, and concise syntax, Python has
>>> from java.applet
Applet
remained
a
premier
programming
languageButton,
for more than
a decade,BorderLayout
and is used by
>>> from java.awt import Frame, List,
Panel,

novices and professionals alike. In particular, its close relationship to Java(TM) makes
thethat
twosubclasses
languages,
when used
in combination, ideal for Web
Define a Python class
Applet
( java.applet.Applet
). and distributed enterprise
application development.

>>> class MyApplet (Applet):


This tutorial begins with coverage of some of the basics of Python programming. Using
...
def __init__(self):
plentyself.list
of skill-building=exercises
and interactive programming sessions, this book will
...
List()
help
those
new
to
programming
develop
...
self.add(self.list) an understanding of concepts and practical
techniques.
For experienced programmers, the book demonstrates Python's breadth of
...
def init(self):
capabilities
and shows the ways that Python
interfaces with Java APIs for professional
...
self.list.add("Init
called")
application development.
...
def destroy(self):
...
self.list.add("Destroy called")
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
...
def start(self):
and Enterprise
Applications with Jython called")
covers important topics such as:
...
self.list.add("Start
...
def stop(self):
...
self.list.add("Stop
called")
Fundamental programming concepts,
including statements, expressions,
...
interpreters, and compilers
We can also add a browserPython
simulator
(a "fake
browser").
A simulator
allows us to
activate theclasses,
lifecycleerrors,
basics,
including
operators,
string formatting,
namespaces,
notifications, and thus simulate
events,
by
hitting
the
corresponding
buttons.
and exceptions
Create a frame and a MyApplet
instance.programming
Add the instance
to the frame.
Object-oriented
concepts

>>> fakeBrowser =FileFrame("Fake


Browser")
input/output
>>> applet = MyApplet()
>>> fakeBrowser.add(applet,
BorderLayout.CENTER)
Python's intrinsic functions
Create four buttons, and add
them to the
toolbar.and
The
buttons correspond
Formatting,
parsing,
manipulating
strings to the individual lifecycle notifications
the applet receives from the browser.
Interfacing with the Java APIs and working with Java Streams

>>> b = Button
#Shortcut for Button class
Python
and Java Swing
to create GUIs b("stop"), b("init"),
>>> start, stop, Using
init,
destroy
= b("start"),
b("destroy")
Working stop,
with SQLinit,
and JDBC(TM)
>>> buttons = (start,
destroy)
>>> toolbar = Panel()
and Java applets
>>> for button inPython
buttons:
...
toolbar.add(button)
In addition, the book contains instructions for downloading and installing the Python
...
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
java.awt.Button[button0,0,0,0x0,invalid,label=start]
and numerous code samples make this book a useful learning experience.
java.awt.Button[button1,0,0,0x0,invalid,label=stop]
java.awt.Button[button2,0,0,0x0,invalid,label=init]
Whether you are a sophisticated computer user new to programming or a serious
java.awt.Button[button3,0,0,0x0,invalid,label=destroy]
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.
Add the toolbar to the frame in the north region, and make the frame visible.

777

>>> fakeBrowser.add(toolbar, BorderLayout.NORTH)


>>> fakeBrowser.pack()
>>> fakeBrowser.visible=1

Python Programming with the Java Class Libraries: A Tutorial for Building

Create handlers for the


buttons
that call theApplications
lifecycle methods
pressed.
Web
and Enterprise
withwhen
Jython

>>>
...
>>>
...
>>>
...
>>>
...

By Richard Hightower

def __init(event):applet.init()
Publisher: Addison Wesley
def __destroy(event):applet.destroy()
Pub Date: June 28, 2002
ISBN: 0-201-61616-5
def of__start(event):applet.start()
Table
Pages: 640
Contents

def __stop(event):applet.stop()

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
and professionals alike. In particular, its close relationship to Java(TM) makes
Register the handlersnovices
to the buttons.
the two languages, when used in combination, ideal for Web and distributed enterprise
>>> handlers=(__start,__stop,__init,__destroy)
application development.

>>> for i in range(0,4):


This tutorial begins with coverage of some of the basics of Python programming. Using
...
buttons[i].actionPerformed=handlers[i]
plenty of skill-building exercises and interactive programming sessions, this book will
...
help those new to programming develop an understanding of concepts and practical
Test the applet by hitting
the buttons.
Your browser
simulator should
lookdemonstrates
like Figure 18-2.
techniques.
For experienced
programmers,
the book
Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application
development.
Figure
18-2. Simulated Lifecycle Event Notification
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
Object-oriented programming concepts
Compiling an Applet
File input/output
To compile a Jython class as a Java class, you have to put it in a module of the same name. Thus, MyApplet.py
contains the MyApplet class.
Here's
the code:
Python's
intrinsic
functions

from java.applet Formatting,


import parsing,
Applet
and manipulating strings
from java.awt import List
the Javathat
APIs and
working with Java
# Define aInterfacing
Pythonwith
class
subclasses
theStreams
Applet class.
# (java.applet.Applet)
Using Python and Java Swing to create GUIs

class MyApplet (Applet):


Working with SQL and JDBC(TM)
def __init__(self):
self.list
List()
Python and=Java
applets
self.add(self.list)
def init(self):
In addition, the book contains instructions for downloading and installing the Python
self.list.add("Init
called")
language
and the Java Development
Kit (JDK). Terminology, definitions, explanations,
def destroy(self):
and numerous code samples make this book a useful learning experience.
self.list.add("Destroy called")
def start(self):
Whether you are a sophisticated computer user new to programming or a serious
self.list.add("Start
called")
application
developer, Python Programming
with the Java(TM) Class Libraries will
def stop(self):
give you insight into the power of Python and the know-how to put it to work.
self.list.add("Stop called")

777

if __name__ == "__main__":
from FakeBrowser import FakeBrowser

fakeBrowser
= FakeBrowser()
Python Programming
with the Java Class Libraries: A Tutorial for Building
fakeBrowser.addApplet(MyApplet())
Web and Enterprise Applications with Jython
By Richard Hightower

Notice that the main block imports the FakeBrowser class, which is based on the browser simulator we
created in the last interactive
session. (FakeBrowser isn't listed, but you can look it up in FakeBrowser.py.
Publisher: Addison Wesley
RunningMyApplet.py yields
the same output as before.)
Pub Date: June 28, 2002
ISBN: 0-201-61616-5
To compile
, use
jythonc at the command prompt.
Table MyApplet
of

Contents

Pages: 640

jythonc deep --package com.awl.jython_book --jar myapplet.jar MyApplet.py


Characterized by ease of use, richness of expression, and concise syntax, Python has
We saw how to use Jythonc
in Chapter
1. Note thatlanguage
the package
is specified
as com.awl.Jython_book
remained a premier
programming
for more
than a decade,
and is used by and
novices
and
professionals
alike.
In
particular,
its
close
relationship
to
Java(TM)
makes
that the classes are put in a JAR file called my.applet.jar. (A Java archive file is a zip file but
with a manifest
denoting that MyApplet
an applet.)when used in combination, ideal for Web and distributed enterprise
the twoislanguages,
application development.
Because we added FakeBrowser to the main block, we can run MyApplet as a standalone application
This tutorial begins
coveragethe
of following
some of the
of Python
programming. Using
(com.awl.Jython_book.MyApplet)
simplywith
by entering
at basics
the command
line:
plenty of skill-building exercises and interactive programming sessions, this book will
java -classpath
%CLASSPATH%;myapplet.jar
com.awl.jython_book.MyApplet
help those
new to programming develop an understanding
of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
which puts Jython.jar
and myapplet.jar
in the
needswith
Jython.jar
in order
to run.
capabilities
and shows
theclasspath.
ways thatMyApplet
Python interfaces
Java APIs
for professional
application development.
We're not done yet. We want to run this applet "embedded" in an HTML file inside a browser, so we have to
configure the Applet
tag Programming
for applets. with the Java(TM) Class Libraries: A Tutorial for Building Web
Python
and Enterprise Applications with Jython covers important topics such as:
First, some exercises:
Fundamental programming concepts, including statements, expressions,
Add a Clear button to the applet that clears the list in MyApplet .
interpreters, and compilers
Recompile the applet. Hint: You can use a batch file called compile.bat for this, but be sure to open and
Python basics, including operators, string formatting, namespaces, classes, errors,
study it first.
and exceptions
Run the applet in FakeBrowser with the Java interpreter. Hint: Use a batch file called run.bat, but
Object-oriented programming concepts
open and study it first.

File input/output
Python's intrinsic functions

No Archive Tag

Formatting, parsing, and manipulating strings


If your browser doesn't support the archive tag, or if you're having problems compiling your applet, try using the all
Interfacing
with arguments
the Java APIs
and working
withtoJava
Streams
orcore arguments to jythonc
. These
instruct
jythonc
include
JythonC.jar in the applet's jar file.
Using Python and
Java Swing to create GUIs --jar myapplet.jar MyApplet.py
jythonc core --package
com.awl.Jython_book
or

Working with SQL and JDBC(TM)

Python and Java


applets
jythonc all --package
com.awl.Jython_book
--jar myapplet.jar MyApplet.py
In addition, the book contains instructions for downloading and installing the Python
andinthean
Java
Development
Embedding anlanguage
Applet
HTML
PageKit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
To embed MyApplet in a Web page, we need the applet tag, which takes the following form:
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
<applet
give you insight into the power of Python and the know-how to put it to work.
code="com.awl.jython_book.MyApplet"

codebase=".\jpywork"
archive="..\..\lib\jython.jar"
width=400
height=400

777

>

Python Programming with the Java Class Libraries: A Tutorial for Building

<param name="hello"
value="hello">
Web and Enterprise
Applications with Jython
If you don't By
have
Java-enabled browser, you need to get one!
RichardaHightower
</applet>
Publisher: Addison Wesley

Each parameter takes a Pub


name/value
pair, and each has a purpose:
Date: June 28, 2002

Table of
Code holds
Contents

ISBN: 0-201-61616-5

the

Pages:
name
of the640
applet

class (in our case,

com.awl.Jython_book.MyApplet.class).
Characterized by ease of use, richness of expression, and concise syntax, Python has

Codebase holds
the relative
path
of the code language
basethefor
root
directory
which
browser
remained
a premier
programming
more
than afrom
decade,
andthe
is used
by loads the
novices
and professionals
alike. In particular,
its closebase,
relationship
to Java(TM)
makes
Java classes and
resources
it needs. It's equivalent
to the document
from which
the browser
loads the
the
two
languages,
when
used
in
combination,
ideal
for
Web
and
distributed
enterprise
document form. In other words, if an applet is loaded from www.jython.org\demo\applet.html, the
document baseapplication
is loaded from
www.jython.org\demo. (Remember, the default operation for jythonc is
development.
to put the class files in the jpywork subdirectory of the current directory.)
This tutorial begins with coverage of some of the basics of Python programming. Using
archive holds
theofname
of any zipexercises
or jar files
thisinteractive
applet uses-in
our case, sessions,
\lib\jython.jar,
which
plenty
skill-building
and
programming
this book
willholds
helpthat
those
newneeds.
to programming
understanding
and
all of the classes
Jython
Make sure develop
you haveanthe
same versionofofconcepts
Jython.jar
aspractical
the one you
bookversion
demonstrates
Python'swith
breadth
compile with. techniques.
You can getFor
theexperienced
right versionprogrammers,
for whatever the
Python
you're working
fromof
capabilities
and
shows
the
ways
that
Python
interfaces
with
Java
APIs
for
professional
c:\Jython; copy it into c:\Jython_book\scripts\lib.
application development.
width/height holds the width and height of the applet in pixels.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
<param name=value=>
specifies the
applet-defined
(application-specific)
name/value
parameters.
and Enterprise Applications
with
Jython covers
important topics such
as:
The applet Tag and Browsers
Fundamental programming concepts, including statements, expressions,
and compilers
Theapplet tag works ininterpreters,
the applet viewer
( AppletViewer), but to run other browsers you have to
expand it to include the myapplet.jar file in the archive parameter and take out codebase (or set it to a
Python basics, including operators, string formatting, namespaces, classes, errors,
period[.]). The following code, from MyAppletJar.html, works with Internet Explorer and Netscape:
and exceptions

<html>
Object-oriented programming concepts
<body>
<center>
File input/output
<applet
code="com.awl.jython_book.MyApplet"
Python's intrinsic functions
archive="..\lib\jython.jar,myapplet.jar"
Formatting, parsing, and manipulating strings
width=400
height=400
Interfacing with the Java APIs and working with Java Streams
>
<param name="hello" value="hello">
Python and Java Swing
to create GUIs
If you don't haveUsing
a Java-enabled
browser,
you need to get one!
</applet>
Working with SQL and JDBC(TM)
</center>
</body>
Python and Java applets
</html>
In addition, the book contains instructions for downloading and installing the Python
Putting the class fileslanguage
in a jar file
downloading.
Unfortunately,
however, AppletViewer
doesn't
andspeeds
the Java
Development
Kit (JDK). Terminology,
definitions, explanations,
recognize the archive
parameter.
This
code
(from
MyApplet.html)
does
work
with
AppletViewer
as
and numerous code samples make this book a useful learning experience.
well as Internet Explorer and Netscape, although its download time is longer than that of jar files.
Whether you are a sophisticated computer user new to programming or a serious
<html>
application developer, Python Programming with the Java(TM) Class Libraries will
<body>
give you insight into the power of Python and the know-how to put it to work.

<center>
<applet
code="com.awl.jython_book.MyApplet"
codebase=".\jpywork"

777

archive="..\..\lib\jython.jar"
Python Programming with the Java Class Libraries: A Tutorial for Building
width=400 Web and Enterprise Applications with Jython
height=400 ByRichard Hightower
>
<param name="hello"
value="hello">
Publisher: Addison
Wesley
If you don't have
a
Java-enabled
browser, you need to get one!
Pub Date: June 28, 2002
</applet>
ISBN: 0-201-61616-5
Table of
</center>

Pages: 640
Contents
</body>
</html>
Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
Running MyApplet
with and
AppletViewer
novices
professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
TheAppletViewer
utility, which
ships with the JDK, allows developers to run applets without a browser. It
application
development.
supports a subset of the Netscape and Internet Explorer HTML tags that are associated with a Java applet.
This tutorial begins with coverage of some of the basics of Python programming. Using
To run AppletViewer
from
the command
line doand
this:
plenty of
skill-building
exercises
interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
appletviewer techniques.
MyApplet.html
For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
In Netscape or Internet Explorer, open the file from the File\Open menu item. You can use the applet with either
application development.
MyApplet.html or MyApplet.Jar.html.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web

Configuring Applet
Behavior
and Enterprise
Applications with Jython covers important topics such as:
An applet can be customized. The following HTML, for example, defines two applet-specific parameters,
Fundamental programming concepts, including statements, expressions,
"color" and "hello":
interpreters, and compilers

<html>
Python basics, including operators, string formatting, namespaces, classes, errors,
<body>
and exceptions
<center>
<applet
Object-oriented programming concepts
code="com.awl.jython_book.MyApplet"
codebase=".\jpywork"
File input/output
archive="..\..\lib\jython.jar"
width=400
Python's intrinsic functions
height=400
Formatting, parsing, and manipulating strings
>
<param name="hello" value="hi mom">
Interfacing
with the Java APIs and working with Java Streams
<param name="color"
value="blue">
If you don't have a Java-enabled browser, you need to get one!
Using Python and Java Swing to create GUIs
</applet>
</center>
Working with SQL and JDBC(TM)
</body>
</html>
Python and Java applets
Call the getParameter()
java.applet.Applet
to read and
the applet's
In addition, method
the bookofcontains
instructions for downloading
installingparameters.
the PythonThis
method in turn gets the
parameters
from
theDevelopment
applet stub (AppletStub
).
language
and the
Java
Kit (JDK). Terminology,
definitions, explanations,
and numerous code samples make this book a useful learning experience.

Whether you are a sophisticated computer user new to programming or a serious


Stub
application developer,The
PythonApplet
Programming
with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.
The applet gets the parameter information from AppletStub, which is passed to the Applet
class via the setStub() method by AppletContext.Java.applet. Applet
implementssetStub(), so you don't have to.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
AppletBrowser
Web and Enterprise Applications with Jython
By Richard Hightower

I've created a fully functioning AppletViewer-like application, called AppletBrowser (which we'll
cover later in detail). AppletBrowser implements the needed stub and context. We're going to use it in our
interactive sessions. Publisher: Addison Wesley
Pub Date: June 28, 2002

ImportJApplet, and create


an instance
of it.
ISBN:
0-201-61616-5

Table of
Contents

Pages: 640

>>> from javax.swing import JApplet


>>> applet = Characterized
JApplet()by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
ImportAppletBrowser
andprofessionals
create an instance
novices ,and
alike. of
Init.
particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise

>>> from AppletBrowser import AppletBrowser


application development.
>>> browser = AppletBrowser()

This tutorial begins with coverage of some of the basics of Python programming. Using
Add the applet instance to AppletBrowser to simulate its loading into AppletViewer or another
plenty of skill-building exercises and interactive programming sessions, this book will
Java-enabled browser.
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
>>> browser.addApplet(applet)
capabilities and shows the ways that Python interfaces with Java APIs for professional
application
Get the color parameter
fromdevelopment.
the applet.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
>>> color = applet.getParameter("color")
and Enterprise Applications with Jython covers important topics such as:
>>> print color
"blue"
programming concepts, including statements, expressions,
Get the hello parameterFundamental
from the applet
interpreters, and compilers

>>> hello = applet.getParameter("hello")


>>> print hello Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
"hi mom"
Object-oriented
The other parameterscodebase
,codeprogramming
,archive, concepts
and so forthwhich aren't defined by the param
keyword, are accessible through applet.getParameter().
File input/output
Getarchive,code, and codebase from the applet, and print them out.
Python's intrinsic functions

>>> code = applet.getParameter("code")


Formatting, parsing, and manipulating strings
>>> codebase = applet.getParameter("codebase")
>>> archive = applet.getParameter("archive")
Interfacing with the Java APIs and working with Java Streams
>>> print (code, codebase, archive)
('com.awl.java_book.MyApplet',
'./jpywork/',
Using Python and Java Swing
to create GUIs '..\..\lib\jython.jar')
Try to get a parameter that Working
doesn't exist.
withgetParameter()
SQL and JDBC(TM) will return None.

>>> print applet.getParameter("my_param")


Python and Java applets
None
In addition, the book contains instructions for downloading and installing the Python
Use parameters to pass
information,
the URL andKit
driver
name
of the database
to whichexplanations,
the applet
language
and thesuch
JavaasDevelopment
(JDK).
Terminology,
definitions,
connects, or the COSand
naming
service
where
it looks
forthis
its stubs.
the applet's
parameters customize its
numerous
code
samples
make
book aBasically,
useful learning
experience.
behavior.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
An Applet Example
give you insight into the power of Python and the know-how to put it to work.
The following code (from context\MyApplet.py) shows an applet that does what the applet in the previous
session does, but in a module that you can compile and use in a browser or in AppletViewer. (Pay special
attention to the showParameters() method.)

777

from javax.swing
JApplet
Pythonimport
Programming
with the Java Class Libraries: A Tutorial for Building
from javax.swing
import
JList,
DefaultListModel,
JScrollPane
Web and
Enterprise
Applications
with Jython
By Richard Hightower

# Define a Python class that subclasses the JApplet class


# (javax.swing.JApplet)
Publisher: Addison Wesley
class MyApplet Pub
(JApplet):
Date: June 28, 2002
def __init__(self):
ISBN: 0-201-61616-5
Table of
self.list
= DefaultListModel()

Pages: 640
Contents
_list = JList(self.list)
self.contentPane.add(JScrollPane(_list))
Characterized
by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by

def print(self,
str): alike. In particular, its close relationship to Java(TM) makes
novices and professionals
theself.list.addElement(str)
two languages, when used in combination, ideal for Web and distributed enterprise
application development.

def init(self):
self.print("Init
called")
This
tutorial begins with coverage
of some of the basics of Python programming. Using
self.showParameters()
plenty
of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical

def destroy(self):
techniques. For experienced programmers, the book demonstrates Python's breadth of
self.print("Destroy
capabilities
and shows the ways thatcalled")
Python interfaces with Java APIs for professional
application development.

def start(self):
Python
Programming with the Java(TM)
Class Libraries: A Tutorial for Building Web
self.print("Start
called")
and Enterprise Applications with Jython covers important topics such as:

def stop(self):
self.print("Stop called")

Fundamental programming concepts, including statements, expressions,


interpreters, and compilers
def showParameters(self):

# Get the color parameter.


Python basics, including operators, string formatting, namespaces, classes, errors,
color
= "color", self.getParameter("color")
and exceptions
# Get the hello parameter.
hello
= "hello",
self.getParameter("hello")
Object-oriented
programming
concepts
# Get the myparam parameter.
myparam
= "myparam", self.getParameter("myparam")
File input/output
codebase = "codebase", self.getParameter("codebase")
Python's=intrinsic
functions
params
(color,
hello, myparam, codebase)
for param in params:
Formatting, parsing, and
manipulating
self.print("%s
equals
%s"strings
% param)
Interfacing with the Java APIs and working with Java Streams

if __name__ == "__main__":
from AppletBrowser
import
AppletBrowser
Using Python and
Java Swing
to create GUIs
fakeBrowser = AppletBrowser()
fakeBrowser.addApplet(MyApplet())
Working with SQL and JDBC(TM)

This version of AppletViewer


, which
Python and
Java derives
applets from JApplet, uses showParameters() to call the
__init__ method. ShowParameters() shows the parameters in a listbox in much the same way as in
In addition, the book contains instructions for downloading and installing the Python
the interactive session.
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
As an exercise, compile
and run context\MyApplet.py
thebook
applet
viewerlearning
or Netscape
Navigator. (You'll have
and numerous
code samples makeinthis
a useful
experience.
trouble running it in Internet Explorer because it uses Swing classes. To get it right you'll have to do some extra
Whether
you areof
a sophisticated
computer user
to v.1.1.4.)
programming or a serious
configuring and download
a version
Swing that's compatible
withnew
JVM
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

Assume Nothing with Browsers

Publisher:you
Addison
Wesley
With applet development
can make
very few assumptions about the browser. For example,
Date:support
June 28,
2002
J2ME and older Pub
browsers
only
AWT.
Table of
Contents
Reading
Applet

ISBN: 0-201-61616-5
Pages: 640

Files

Characterized by ease of use, richness of expression, and concise syntax, Python has
For security reasons,remained
you can't aread
files programming
from an appletlanguage
if they'refor
on more
the client's
driveand
(unless
youbyconfigure
premier
than ahard
decade,
is used
Java security to allownovices
this). However,
you can alike.
read them
from the its
Web
server
that serves
applet to
the client.
and professionals
In particular,
close
relationship
to the
Java(TM)
makes
We won't cover Javathe
security
here, but Iwhen
do recommend
that you read
thefor
online
documentation
at the
two languages,
used in combination,
ideal
Websecurity
and distributed
enterprise
Javasoft Web site. application development.
The way to read applet
files
is with
a URL.
see how
with aofsample
file of
located
onprogramming.
the Jython Web
server.
This
tutorial
begins
withWe'll
coverage
of some
the basics
Python
Using
(If you have your own
Webofserver,
you can exercises
skip this next
plenty
skill-building
and section.)
interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
The Python Web techniques.
Server
For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
Python's Web serverapplication
can be found
in the SimpleHTTPServer module. Here's what to do to get it up and running:
development.

>>> from SimpleHTTPServer


import
test Class Libraries: A Tutorial for Building Web
Python Programming with
the Java(TM)
>>> test() and Enterprise Applications with Jython covers important topics such as:
Serving HTTP on port 8000 ...
programming
concepts,
including
statements,
SimpleHTTPServer deliversFundamental
HTML pages
from the current
working
directory,
so to runexpressions,
the Web server for our
interpreters,
and compilers
HTML page we have to start
a DOS prompt
and run the module in the .\scripts\chap18\context subdirectory.
Then we can access the applet with Netscape Navigator by entering the URL
Python basics, including
operators,
string formatting, namespaces,
classes,
errors,
http://your_ip_address:8000/MyAppletJar.html,
replacing
"your_ip_address
" with your
server's
address.
and
exceptions
On Windows NT/98, you can find that address via the ipconfig command.

C:\>ipconfig

Object-oriented programming concepts


File input/output

Windows 98 IP Configuration
Python's intrinsic functions

0 Ethernet adapter :

Formatting, parsing, and manipulating strings

IP Address. . . . . . . . . : 0.0.0.0
Subnet Mask
. . with
. .the.Java
. APIs
. . and
: working
0.0.0.0
Interfacing
with Java Streams
Default Gateway . . . . . . :
Using Python and Java Swing to create GUIs
(To use Internet Explorer you need the Java plug-in or the JFC Swing package. See the Javasoft Web site for
Working with SQL and JDBC(TM)
more information.)
and Java
If you're running the PythonPython
Web server
andapplets
the browser on the same machine, use the URL
http://local_host_:8000/MyAppletJar.html. However, you'll be better off using the IP address or the domain
addition,
the book NT/98,
containsthe
instructions
downloading
and installing
theofPython
name service (DNS)In
entry.
On Windows
DNS entryfor
usually
corresponds
to the name
your
language
and
the
Java
Development
Kit
(JDK).
Terminology,
definitions,
explanations,
machine, which replaces "localhost" in the URL.
and numerous code samples make this book a useful learning experience.
If you use another Web server, you may have to adjust the port setting to match it. The default port for HTTP is
you are card,
a sophisticated
computer
user
new to(programming
or a serious
80. Also, if you don'tWhether
have a network
you can use
the applet
browser
AppletBrowser
), which
application
developer,
Python
Programming
with
the
Java(TM)
Class
Libraries
will
simulates a browser talking to a Web server. ( AppletBrowser can do this even on a separate
machine.)
give
you
insight
into
the
power
of
Python
and
the
know-how
to
put
it
to
work.
Lastly, you can use the File/Open menu item in Netscape Navigator to open the HTML containing the
"embedded" applet.

777

Working with URLs in an Interactive Session

To read a file from the


serverProgramming
you need the URL
which you
canLibraries:
find in theAjava.net
package.
The
Python
withclass,
the Java
Class
Tutorial
for Building
Applet class has methods
that
return both
the document
baseJython
URL and its code base counterpart. URL's
Web and
Enterprise
Applications
with
openStream() method
returns
an input stream, which means that if you have a file called data.dat you can
By Richard
Hightower
append it to one of URL's methods.
Publisher: Addison Wesley

ImportJApplet fromPub
javax.swing.
Date: June 28, 2002
ISBN: 0-201-61616-5
>>> Table
fromof javax.swing
import JApplet

Pages: 640
>>> Contents
applet = JApplet()

Characterized
byapplet
ease ofa use,
richness
expression,
andthe
concise
syntax,
Python has
Use AppletBrowser
to give the
context
and aofstub
(to simulate
applet's
environment).
remained a premier programming language for more than a decade, and is used by
novices and professionals
In particular, its close relationship to Java(TM) makes
>>> from AppletBrowser
importalike.
AppletBrowser
the
two
languages,
when
used
in
combination, ideal for Web and distributed enterprise
>>> browser = AppletBrowser()
application
development.
>>> browser.addApplet(applet)
tutorial
begins
with coverage of some of the basics of Python programming. Using
Show the code base This
(using
Java and
Jython).
plenty of skill-building exercises and interactive programming sessions, this book will
>>> applet.getCodeBase()
help those new to programming develop an understanding of concepts and practical
file:/C:/book/scripts/chap18/context/jpywork/
techniques. For experienced programmers, the book demonstrates Python's breadth of
>>> applet.codeBase
capabilities and shows the ways that Python interfaces with Java APIs for professional
file:/C:/book/scripts/chap18/context/jpywork/
application development.
Show the document Python
base (using
Java and Jython).
Programming
with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

>>> applet.getDocumentBase()
file:/C:/book/scripts/chap18/context/
Fundamental programming concepts, including statements, expressions,
>>> applet.documentBase
interpreters, and compilers
file:/C:/book/scripts/chap18/context/

Python basics, including operators, string formatting, namespaces, classes, errors,


and exceptions
Java.net.URL
Object-oriented programming concepts
The Java API documentation will tell you what you want to know about java.net.URL. I'll just show you its form:
File input/output

>>> url = applet.documentBase


>>> url.class Python's intrinsic functions
<jclass java.net.URL at 960293886>
>>> dir (url.class)
Formatting, parsing, and manipulating strings
['ref', 'file', '__init__', 'toExternalForm',
Interfacing with the Java'content',
APIs and working
with Java Streams
'setURLStreamHandlerFactory',
'getFile',
'sameFile',
'getProtocol', 'openStream', 'getContent', 'protocol', 'getHost', 'port',
Using
Python and'getRef',
Java Swing to create
GUIs
'openConnection',
'host',
'getPort']
Working with SQL and JDBC(TM)
There are two files in the context directory with the name data.dat. One is the context itself and is associated
with the document base URL;
the and
otherJava
is inapplets
the jpywork subdirectory and is associated with the code base URL.
Python
ImportURL from java.net.
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
>>> from java.net
import
URL make this book a useful learning experience.
and numerous
code samples
GetdocumentBaseURL
the aapplet.
Whetherfrom
you are
sophisticated computer user new to programming or a serious

application developer, Python Programming with the Java(TM) Class Libraries will

>>> documentBaseURL
= applet.documentBase
give you insight into the power of Python and the know-how to put it to work.
Create a URL instance based on documentBaseURL's context.

777

>>> data_dat = URL(documentBaseURL, "data.dat")


>>> data_dat

file:/C:/book/scripts/chap18/context/data.dat
Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython

Get the associated input


stream.Hightower
By Richard

>>> instream = data_dat.openStream()


Publisher: Addison Wesley

Pub
June
28, 2002
Import the classes needed
toDate:
read the
data.dat
text file.
ISBN: 0-201-61616-5

Table of

>>> Contents
from java.io Pages:
import
640 BufferedReader, InputStreamReader
Create a BufferedReader
stream
by of
chaining
an InputStreamReader
instance
instream
Characterized
by ease
use, richness
of expression, and concise
syntax,toPython
has .
(See the Java API online
documentation
for more information
thesethan
classes.)
remained
a premier programming
languageabout
for more
a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
>>> data_reader
= languages,
BufferedReader(InputStreamReader(instream))
the two
when used in combination, ideal for Web and distributed enterprise
application development.
Show the contents of the file.

This tutorial begins with coverage of some of the basics of Python programming. Using

>>> data_reader.readLine()
plenty of skill-building exercises and interactive programming sessions, this book will
'Hello from the Document base!'

help those new to programming develop an understanding of concepts and practical


experienced
programmers, the book demonstrates Python's breadth of
As an exercise, read techniques.
data.dat in For
the code
base URL.
capabilities and shows the ways that Python interfaces with Java APIs for professional
development.
The great thing aboutapplication
URL is that
it works with the HTTP and FTP protocols. This means that you can download
file data from anywhere on the Internet. The question is, why do this?
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
Enterprise
Applications
Jythonsomewhere
covers important
such
as:
The answer is that anand
application
that
doesn't get with
data from
is prettytopics
useless.
Consider
the advantages
of adding applet capabilities to the address book application. With them, a user could access her address book
from any location on the Internet. We'll see how in the next section.
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers

Transforming the Address Book Application into an Applet

Python basics, including operators, string formatting, namespaces, classes, errors,


and exceptions
What we're going to do is convert
AddressMain, which is currently a form, into an applet. Later we'll make
changes to AddressModel so that it can deal with URLs instead of files. This means that it will be able to
Object-oriented programming concepts
read and write to any files to which it refers, including any file transmitted over the HTTP protocol.

File input/output

Changes to AddressMain
Python's intrinsic functions
First let's make it so AddressMain derives from an applet instead of a frame.
Formatting, parsing, and manipulating strings

class AddressMain(JApplet):

Interfacing with the Java APIs and working with Java Streams

Now let's add the __init__ and __destroy__ methods. __init__ gives us access to the database,
Using Python and Java Swing to create GUIs
which we need to initialize AddressModel.__destroy__ calls AddressModel's
writeAddress() function,
which
addresses
out to a file (if the protocol supports this).
Working
withwrites
SQL and
JDBC(TM)

def init(self): Python and Java applets


url=None
To contains
hold instructions
the document
base and
url.
In addition, the#book
for downloading
installing the Python
try:

language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.

url = self.getDocumentBase()
except:Whether you are a sophisticated computer user new to programming or a serious
print
"Unable
toPython
getProgramming
documentwith
base
URL" Class Libraries will
application
developer,
the Java(TM)
give you insight into the power of Python and the know-how to put it to work.

def init(self):

777

url=None

# To hold the document base url.

try:

Python Programming with the Java Class Libraries: A Tutorial for Building

url
= self.getDocumentBase()
Web and
Enterprise Applications with Jython
except:ByRichard Hightower
print "Unable to get document base URL"
Publisher: Addison Wesley

Now, because we have to move some of the code out of __init__ , we need to create another method to
Pub Date: June 28, 2002
initialize the GUI components based on AddressModel.

Def

ISBN: 0-201-61616-5
Table of
Pages:
640
initGUI(self):
Contents

# Move to the first address in

Characterized
by ease
of use,
richness of expression, and concise syntax, Python has
# the list
and
table.
remained
a
premier
programming
If self.model.getSize() > 0:language for more than a decade, and is used by
novices
and professionals alike. In particular, its close relationship to Java(TM) makes
Self.addresses.setSelectIndex(0)
the
two
languages,
when used in combination, ideal for Web and distributed enterprise
Address
= self.model.getAddressAt(0)
application
development.
Self.form.set(address)
This tutorial begins with coverage of some of the basics of Python programming. Using

Changes to AddressModel
plenty of skill-building exercises and interactive programming sessions, this book will

help those new to programming develop an understanding of concepts and practical


We've made our address
book application
fairly modular,
so it's the
easybook
to add
support forPython's
reading from
a URL.
techniques.
For experienced
programmers,
demonstrates
breadth
of In
fact, it takes just three
lines of code.
We now
AddressURL
(from
capabilities
and shows
thehave
waysa class,
that Python
interfaces with
Java APIs for professional
AddressBook\AddressModel.py),
that has its own readAddresses() and writeAddresses()
application development.
methods, which means that we no longer have to import them from AddressUtils.py.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
Here's the modified AddressBook\AddressModel.py
and Enterprise Applications withmodule:
Jython covers important topics such as:

from address import Address


Fundamental programming concepts, including statements, expressions,
...
interpreters, and compilers
...
from AddressURL import AddressURL
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
class AddressModel(AbstractTableModel,
ListModel):

"""The AddressModel is both a ListModel and a


Object-oriented programming concepts
TableModel."""
File input/output

def __init__(self, url):


"""Initialize
the Address model.
Python's intrinsic functions
Read the dictionary from the file."""
Formatting, parsing, and manipulating strings

self.dict = None
# holds the dictionary of addresses.
Interfacing =
with
the Java APIs
and working
with
Java Streams
self.list
None
# holds
the
sorted
list of names,
# which are keys
Using Python and Java Swing
createthe
GUIs dictionary.
# to
into
Working with SQL and JDBC(TM)

self.listeners = [] # to hold list of


Python and Java applets # ListModelListeners
AddressURL(url)
Inself.io
addition, the=book
contains instructions for downloading and installing the Python
the addresses
the AddressURL
class.
language and#theRead
Java Development
Kit (JDK).from
Terminology,
definitions, explanations,
self.dict
= samples
self.io.readAddresses()
and
numerous code
make this book a useful learning experience.
...Whether you are a sophisticated computer user new to programming or a serious
...application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.
def writeAddresses(self):
"""Write the address data to the file."""
self.io.writeAddresses(self.dict)
AddressURL

777

Python Programming with the Java Class Libraries: A Tutorial for Building

AddressURL usesWeb
the openStream()
method to read a file from a URL. It writes to the file as well if its
and Enterprise Applications with Jython
underlying protocol (HTTP,
FTP,
file,
etc.)
provides
the necessary support. Using getOutputStream()
By Richard Hightower
(fromjava.net.URLConnection),AddressURL gets the file's associated output stream.
Publisher: Addison Wesley

Take a look at AddressBook\AddressURL.py. Be sure to read the comments.


Pub Date: June 28, 2002

ISBN:ObjectInputStream,
0-201-61616-5
fromTable
java.io
import
IOException
of

Pages:ObjectOutputStream,
640
from
java.io
import
File, FileOutputStream
Contents
from java.net import URL, UnknownServiceException
Characterized
by ease of
use, richness of expression, and concise syntax, Python has
from string import
split,
join
remained
a
premier
programming
language for more than a decade, and is used by
class AddressURL:
novices
and
professionals
alike.
In
particular, its close relationship to Java(TM) makes
def __init__(self, url, filename="./addr.dat"):

the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
# Set the url. If the url does not exist,

# create one based on the current


This tutorial #
begins
with coverage
of some
of the basics of Python programming. Using
directory
and
filename.
plenty
of
skill-building
exercises
and
interactive
programming sessions, this book will
if(url):
help those new
to
programming
develop
an
understanding
of concepts and practical
self.url = URL(url, filename)
techniques.
For
experienced
programmers,
the
book
demonstrates
Python's breadth of
else:
capabilities and
shows
the
ways
that
Python
interfaces
with
Java
APIs
for professional
file = File(filename)
application development.
self.url = file.toURL()
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

def readAddresses(self):

"""
ReadFundamental
in a dictionary
of addresses.
programming concepts,
including statements, expressions,
Usesinterpreters,
URL.openStream()
and compilers
"""
filePython
= None
to hold
thestring
file
inputnamespaces,
stream classes, errors,
basics, #
including
operators,
formatting,
and exceptions

# Use try/finally to work with the file.


Object-oriented
programming
concepts
# If the
file does
not work for any

# reason then close it.

try:File input/output

# Try to read in the addresses from the


# file. If you can't read the addresses
# and
then
print strings
an error message.
Formatting, parsing,
manipulating
try:
file
= self.url.openStream()
Interfacing with the
Java APIs
and working with Java Streams
in_stream= ObjectInputStream(file)
Using Python anddict
Java Swing
to create GUIs
= in_stream.readObject()
return dict
Working
with SQL
and JDBC(TM) error:
except
IOException,
print "ERROR reading url: " + self.url
Python and Java applets
print error.class.name
print error.message
In addition, the book contains instructions for downloading and installing the Python
return {}
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
finally:
and numerous code samples make this book a useful learning experience.
if not (file is None): file.close()
Python's intrinsic functions

Whether you are a sophisticated computer user new to programming or a serious

def writeAddresses(self,
dict): with the Java(TM) Class Libraries will
application developer, Python Programming
"""
give you insight into the power of Python and the know-how to put it to work.
Write the addresses instances
in the dictionary to a
file.

777

The writeAddresses
method
uses
Python
Programming with the
Java Class
Libraries: A Tutorial for Building
URL.openConnection().getOutputStream(),
and
Web
and Enterprise Applications with Jython
attempts
to write the dictionary of
By
Richard Hightower
addresses to a file.
Publisher: Addison Wesley

Table of
Contents

IfPubthe
fails because the protocol
Date:writing
June 28, 2002
doesISBN:
not0-201-61616-5
support writing, then
writeAddresses
checks to see if
Pages: 640
the protocol is file protocol. If it is file
protocol,by ease
writeAddresses
calls and concise syntax, Python has
Characterized
of use, richness of expression,
writeAsFile,
which
remained a premier programming language for more than a decade, and is used by
opensandaprofessionals
file using
FileOutputStream.
novices
alike. In
particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
"""
application
development.

# to hold the output file output stream.

file=None
This
tutorial begins with coverage of some of the basics of Python programming. Using
# Use try/finally
to write
the sessions,
instances
plenty of skill-building
exercises and interactive
programming
this book will
# to
toprogramming
a file. develop an understanding of concepts and practical
help those new
# If
all else
failsthethen
close
techniques. For
experienced
programmers,
book demonstrates
Python's breadth of
# the
capabilities and
showsfile
the waysobject.
that Python interfaces with Java APIs for professional
try:
application
development.
# Write the address instances in dict
Python Programming with
Libraries: A by
Tutorial
for Building Web
# the
to Java(TM)
a fileClass
specified
filename.
and Enterprise Applications
withthere
Jython covers
topics such
as:
# If
are important
any errors
then

# print an error message.


try:

Fundamental programming
concepts, including
statements, expressions,
urlConnection
= self.url.openConnection()
interpreters, and compilers
file = urlConnection.getOutputStream()

out_stream = ObjectOutputStream(file)

Python basics, including operators, string formatting, namespaces, classes, errors,


out_stream.writeObject(dict)
and exceptions

# If the protocol does not support


# writing,
do this....
Object-oriented programming
concepts
except UnknownServiceException, noservice:
# If the protocol is file,
File input/output
# then write it as a file.
Python's intrinsic functions
if self.url.protocol=='file':
filename=self.url.toString()
Formatting, parsing, and manipulating
strings
self.writeAsFile(filename,
dict)
else:
Interfacing with the Java APIs and working with Java Streams
print noservice.message + self.url
except
IOException,
Using Python and Java Swing to createerror:
GUIs
print "ERR: writing addresses"+ self.url
print
error.class.name
Working with SQL
and JDBC(TM)
print error.message
finally:
Python and Java applets
if(file):file.close()
In addition, the book contains
instructions for
downloading and installing the Python
def writeAsFile(self,
filename,
dict):
language
""" and the Java Development Kit (JDK). Terminology, definitions, explanations,
and
numerous
codeasamples
make this book
useful learning by
experience.
Writes
out
dictionary
of aaddresses
using
Whether
you are a sophisticated computer user new to programming or a serious
FileOutputStream.
application
developer, Python Programming with the Java(TM) Class Libraries will
"""
give you insight
into the power
of Python
and the know-how
to put
it to work.
# Extract
the
filename
from the
URL
# string.
filename = filename[5:]
filename = File(filename)
file = None #to hold the file output stream.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
try:
Web
and Enterprise Applications with Jython
# Write the address instances
By Richard Hightower

Table of
Contents

# in dict to the file.


# If there are any errors
Publisher: Addison Wesley
# then print an error message.
Pub Date: June 28, 2002
try:
ISBN: 0-201-61616-5
file = FileOutputStream(filename)
Pages: 640
out_stream = ObjectOutputStream(file)
out_stream.writeObject(dict)
Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
except IOException, error:
novices and professionals alike. In particular, its close relationship to Java(TM) makes
print "ERROR writing: " + filename
the two languages, when used in combination, ideal for Web and distributed enterprise
print error.class.name
application development.

print error.message
finally:
This tutorial begins with coverage of some of the basics of Python programming. Using
if(file):file.close()
plenty of skill-building
exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. Book
For experienced
programmers, the book demonstrates Python's breadth of
Running the Address
Application
capabilities and shows the ways that Python interfaces with Java APIs for professional
applicationcan
development.
Our address book application
be run as an application or as an applet. Its main block creates an instance of
JFrame and adds an instance of AddressMain to it. Here's part of the code (from
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
AddressBook\AddressMain.py):
and Enterprise Applications with Jython covers important topics such as:

def __windowClosing(event):
event.source.dispose()
Fundamental programming concepts, including statements, expressions,
from java.lang import System
interpreters, and compilers
System.exit(0)
Python basics, including operators, string formatting, namespaces, classes, errors,

if __name__ == "__main__":
and exceptions
mainWindow = Frame("Address book application")
applet = AddressMain()
Object-oriented programming concepts
applet.init()
File input/output
mainWindow.contentPane.add(applet)
mainWindow.windowClosing = __windowClosing
Python's
intrinsic
functions
# Pack
the
frame
and make it visible.
mainWindow.pack()
Formatting, parsing, and300)
manipulating strings
mainWindow.setSize(600,
mainWindow.visible=1
Interfacing with the Java APIs and working with Java Streams

Run the application with AppletBrowser so you can debug and test it as you do the exercises. (The code is
Using Python and Java Swing to create GUIs
fromrun.py.)
Working with SQL and JDBC(TM)

from AppletBrowser import AppletBrowser


from AddressMain Python
import
AddressMain
and Java
applets

applet = AddressMain()
In addition, the book contains instructions for downloading and installing the Python
browser = AppletBrowser()
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.

browser.addApplet(applet)
Whether you are a sophisticated computer user new to programming or a serious
The applet browser provides
AppletContext
and AppletStub
, which
makeClass
available
the will
application
developer, Python Programming
with the
Java(TM)
Libraries
getDocumentBase()
, and
getParameter()
methods, among
give you,resize()
insight into the
power
of Python and the know-how
to put others.
it to work.
Try these exercises:

777

Add an applet parameter that specifies the address book application file name. The name should be

relative to the Python


document
base, and it should
correspond
a specific
address
book. Reviewing
the section
Programming
with the
Java to
Class
Libraries:
A Tutorial
for Building
onAppletBrowser
should help Applications
you here.
Web and Enterprise
with Jython
By Richard Hightower

Get a type-4 JDBC driver so you can get the application to work with an RDBMS system.
Publisher: Addison Wesley

Compile and run AddressBook in a browser.


Pub Date: June 28, 2002

ISBN: 0-201-61616-5

Table
of
Using
AppletBrowser
to Develop Applets

Pages: 640
Contents

To use AppletBrowser
, configure
theoffile
applet.props
the currentand
working
applet.props
Characterized
by ease
use,
richness of in
expression,
concisedirectory.
syntax, Python
has is a
Java properties file that
specifies
the applet's
parameters
(codebase
,code
, etc.).
If you
remained
a premier
programming
language
for more
than,archive
a decade, and
is used
by want,
include a toolbar fornovices
invokingand
theprofessionals
applet's __stop__
,__init__
, and __destroy__
methods.
alike. In particular,
its close
relationship to Java(TM)
makes

the two languages, when used in combination, ideal for Web and distributed enterprise

AppletBrowserapplication
takes the following command-line arguments:
development.

This
tutorial applet.props
begins with coverage
of some of the basics of Python programming. Using
-w writes out
a sample
file
plenty of skill-building exercises and interactive programming sessions, this book will
thoseincludes
new to programming
develop an understanding of concepts and practical
-t runs the help
browser;
a toolbar
techniques. For experienced programmers, the book demonstrates Python's breadth of
and shows
the ways that Python interfaces with Java APIs for professional
-v runs the capabilities
browser in verbose
mode
application development.
-r runs the browser
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
-? shows help
andtext
Enterprise Applications with Jython covers important topics such as:

-prop writes a single parameter to the property file (-propNAME:VALUE)


Fundamental programming concepts, including statements, expressions,

-HTML converts applet.props


HTML page (-HTMLFileName)
interpreters, to
andancompilers
To use the browser in a new
directory,
youincluding
have to execute
it with
theformatting,
w option.namespaces,
This createsclasses,
an applet.props
Python
basics,
operators,
string
errors,
file with a code base that corresponds
to the current working directory.
and exceptions
Here's the code to create anObject-oriented
HTML file called
AddressBook.html:
programming
concepts

C:\jython_book\scripts\chap18\AddressBook>jython
AppletBrowser.
File input/output
pyHTMLAddressBook
Python's intrinsic functions
Here'sAddressBook.html's code:
Formatting, parsing, and manipulating strings

<html>
<body>
<center>

Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs

<applet
Working with SQL and JDBC(TM)
code=com.awl.jython_book.MyApplet
codebase=.\jpywork
Python and Java applets
width=400
height=400
In addition, the book contains instructions for downloading and installing the Python
archive=..\..\lib\jython.jar
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
>
and numerous code samples make this book a useful learning experience.
<param name="color" value="blue">
<param name="hello"
mom">
Whether youvalue="hi
are a sophisticated
computer user new to programming or a serious
If you don't application
have a developer,
Java-enabled
browser,
need to
one!will
Python Programming
withyou
the Java(TM)
Classget
Libraries
</applet></center>
give you insight into the power of Python and the know-how to put it to work.
</body>
</html>

777

Here's how to specify additional applet parameters:

C:\jython_book\scripts\chap18\AddressBook>jython
Python Programming with the Java Class Libraries: AAppletBrowser.
Tutorial for Building
py-propFileName:RicksAddrBook
Web and Enterprise Applications with Jython
By Richard Hightower

Once you add a parameter, it will be available the next time you create an HTML file or use
AppletBrowser. Publisher: Addison Wesley
Pub Date: June 28, 2002
0-201-61616-5
Advanced
Topic:ISBN:
AppletContext
and AppletStub
Table of

Pages: 640

Contents

When an applet is created, it's given a stub via its setStub() method. The stub is the interface between the
Characterized
by ease
of use,
richness
expression,
and the
concise
syntax,
Python
has
applet and the browser.
You don't have
to deal
directly
withofthe
stub because
Applet
class
implements
remained
a
premier
programming
language
for
more
than
a
decade,
and
is
used
by
methods that use it.
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two
languages, when used in combination, ideal for Web and distributed enterprise
Here are AppletStub
's methods:
application development.

appletResize(width,
resizes
theofapplet
This tutorial beginsheight)
with coverage
of some
the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will

getAppletContext()
the applet'sdevelop
contextan understanding of concepts and practical
help those new to gets
programming
techniques. For experienced programmers, the book demonstrates Python's breadth of

getCodeBase()
gets
code the
baseways
URLthat Python interfaces with Java APIs for professional
capabilities
andthe
shows
application development.

getDocumentBase() gets the document base URL


Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

getParameterName() gets an applet parameter


isActive() determines if the applet is active

Fundamental programming concepts, including statements, expressions,


The applet context corresponds to the applet's environment and it can be used to show status, to load other
interpreters, and compilers
documents, and to get access to other applets. The AppletContext's methods are
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
getApplet(name)
gets the applet corresponding to a given name
programming
concepts
getApplets()Object-oriented
gets a collection
of specific applets
Filereturns
input/output
getImage(url)
an image object corresponding to the specified URL
Python's intrinsic
showDocument(url)
shows afunctions
Web page other than the current page and replaces the current page
with it

Formatting, parsing, and manipulating strings

showDocument(url, target) same as above, but specifies the frame target


Interfacing with the Java APIs and working with Java Streams

showStatus(status) shows the status text in the browser


Using Python and Java Swing to create GUIs

AppletBrowser subclasses AppletContext and AppletStub via the classes URL and
Working with SQL and JDBC(TM)
URLClassLoader.
Python and Java applets

AppletBrowser.py
In addition, the book contains instructions for downloading and installing the Python
language
and the Java Development Kit (JDK). Terminology, definitions, explanations,
Here's some of the code
for AppletBrowser.py:
and numerous code samples make this book a useful learning experience.

from java.applet import AppletContext, AppletStub


Whetherimport
you are a sophisticated
computer user JPanel,
new to programming
from javax.swing
JFrame, JButton,
JLabelor a serious
application
developer,
Python Programming
with the Java(TM) Class Libraries will
from javax.swing
import
JTextField,
ImageIcon
give you insight into the power of Python and the know-how to put it to work.
...
...

777

When you use the addApplet() method, AppletBrowser passes a context and calls the applet's
__init__ method.

Python Programming
with the Java Class Libraries: A Tutorial for Building
def addApplet(self,
applet):
Web and Enterprise Applications with Jython
By Richard Hightower

...
...
Wesley
# Set the Publisher:
appletAddison
as the
applet in this instance.
Pub Date:
June 28,as
2002the AppletStub (stub).
# Pass this
instance
ISBN: 0-201-61616-5
# Add this applet
to the frame. Then pack this frame.
Table of
Pages:
640
self.applet
=
applet
Contents
if debug:
Characterized
ease of
use, richness
expression,
and concise
has
print
"Set bythe
stub,
and of
add
the applet
tosyntax,
thePython
container"
remained
a
premier
programming
language
for
more
than
a
decade,
and
is
used
by
applet.setStub(self)
novices and professionals alike. In particular,
its close relationship to Java(TM) makes
self.contentPane.add(self.applet,
BorderLayout.CENTER)
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.

...
applet.init()
This tutorial begins with coverage of some of the basics of Python programming. Using
applet.start()
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
self.pack()
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities passes
and shows
thatand
Python
interfaces
with JavaallAPIs
for professional's
As you can see, AppletBrowser
itselfthe
as ways
the stub
in this
way implements
of AppletStub
application development.
parameters.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
...
and Enterprise Applications with Jython covers important topics such as:
...
def appletResize(self, width, height):
self.setSize(width, height)
Fundamental programming concepts, including statements, expressions,
self.doLayout()
interpreters, and compilers

def getAppletContext(self):
Python basics, including operators, string formatting, namespaces, classes, errors,
return
self
and exceptions
def isActive(self):
Object-oriented programming concepts
return 1
File input/output

def getCodeBase(self):
Python's intrinsic functions
codebase=self.props.getProperty("codebase")
if not codebase:
Formatting, parsing,
andURL(self.docbase,
manipulating strings
return
".")
else:
Interfacing with the Java APIs and working with Java Streams
return URL(self.docbase, codebase)
Using Python and Java Swing to create GUIs

def getDocumentBase(self):
return
self.docbase
Working with
SQL and JDBC(TM)

Python andname):
Java applets
def getParameter(self,
return self.props.getProperty(name)
In addition, the book contains instructions for downloading and installing the Python
languagereturns
and theself
Java ,Development
Kit (JDK). Terminology,
definitions,
explanations,
getAppleContext()
that is, the AppletBrowser
instance,
which means
that
numerousAppletContext
code samples make this
book a useful learning experience.
AppletBrowserand
implements
's methods.
Whether you are a sophisticated computer user new to programming or a serious
...
application developer, Python Programming with the Java(TM) Class Libraries will
...
give you insight
into the power of Python and the know-how to put it to work.
def getApplet(self,
name):
return self.applet #Should return an applet

777

def getApplets(self):
v = Vector()

v.add(self.applet)
Python Programming with the Java Class Libraries: A Tutorial for Building
returnWeb
v.elements()
and Enterprise Applications with Jython
By Richard Hightower

def getImage(self, url):


icon = ImageIcon(url)
Publisher: Addison Wesley
return icon.getImage()
Pub Date: June 28, 2002
ISBN: 0-201-61616-5

of
def Table
showDocument(self,
url):
Pages: 640
Contents
pass

Characterized by ease of use, richness of expression, and concise syntax, Python has

def showDocument(self,
url,
target):
remained a premier
programming
language for more than a decade, and is used by
pass novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise

def showStatus(self,
status):
application development.
self.status.text = status

This tutorial begins with coverage of some of the basics of Python programming. Using
To implement getImage()
,AppletBrowser
usesinteractive
javax.swing.ImageIcon
. The
plenty of skill-building
exercises and
programming sessions, this
book will
getApplet() and
getApplets()
methods
return
the
currently
loaded
applet;
the
showStatus()
help those new to programming develop an understanding of concepts and practical
method shows the status
in a textFor
field
called status
.
techniques.
experienced
programmers,
the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional

AppletBrowser loads the applet specified by the code parameter, as well as all of the jar files specified in
application development.
thearchive tag, into the URLClassLoader class.
...
...

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

def loadApplet(self):
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers

# Create the class loader and get


Python
basics, name.
including operators, string formatting, namespaces, classes, errors,
# the
class
and exceptions
class_loader=self.createClassLoader()
class_name = self.props.getProperty("code")
Object-oriented programming concepts

# Load the class, create an instance


File input/output
# of it,
and add it with addApplet.
if class_name
and class_loader:
Python's intrinsic functions
try:
if debug:
"Loading:
class_name
Formatting,print
parsing, and
manipulating"+
strings
clazz=class_loader.loadClass(class_name)
if debug:
clazz
Interfacing print
with the Java
APIs and working with Java Streams
Using applet
Python and=Java
Swing to create GUIs
clazz.newInstance()
self.addApplet(applet)
with SQLexception:
and JDBC(TM)
except Working
Exception,
global error
Python and Java applets
error = exception
to load
the for
class
"+class_name
Inprint
addition,"Unable
the book contains
instructions
downloading
and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,

def getJars(self):
and numerous code samples make this book a useful learning experience.
urls=[]
#Parse
list
of jarfiles
tag.
Whetherthe
you are
a sophisticated
computer in
user the
new toarchive
programming
or a serious
jarfilesapplication
= self.props.getProperty("archive")
developer, Python Programming with the Java(TM) Class Libraries will
jarfilesgive
= you
split(jarfiles,
",")
insight into the power of
Python and the know-how to put it to work.
# Iterate through the list of jarfiles, and add
# each jarfile as a URL to the urls list.
for jar in jarfiles:

777

url = URL(self.docbase,
jar)
Python Programming with
the Java Class Libraries: A Tutorial for Building
urls.append(url)
Web and Enterprise Applications with Jython
if By
debug:
print "Adding jar file " + `url`
Richard Hightower
return urls
Publisher: Addison Wesley
Pub Date: June 28, 2002

def createClassLoader(self):
ISBN: 0-201-61616-5
Table
of
try:

Pages: 640
Contents
# Get list of URLS for each jar in the
# byarchive
the codebase
and has
Characterized
ease of use,tag.
richnessGet
of expression,
and concise URL,
syntax, Python
#
add
it
to
the
list
of
URLS.
remained a premier programming language for more than a decade, and is used by
# Create alike.
a URL
jarrayits close
to pass
to to
the
novices and professionals
In particular,
relationship
Java(TM) makes
# URLClassLoader
constructor.
the two languages,
when used in combination,
ideal for Web and distributed enterprise
# Get the system class loader to pass to the
application development.
# URLClassLoader constructor.
Create
an instance
ofbasics
URLClassLoader
This tutorial #
begins
with coverage
of some of the
of Python programming. Using
# passing
theandurls
andprogramming
the system
class
plenty of skill-building
exercises
interactive
sessions,
this book will
# to
loader.
help those new
programming develop an understanding of concepts and practical
urls = For
self.getJars()
techniques.
experienced programmers, the book demonstrates Python's breadth of
codebase=self.getCodeBase()
capabilities and shows the ways that Python interfaces with Java APIs for professional
urls.append(codebase)
application development.
urls = array(urls, URL)
Python Programming
with the Java(TM) Class Libraries: A Tutorial for Building Web
loader
= ClassLoader.getSystemClassLoader()
and Enterprise=Applications
with Jython covers important
topics such as:
url_loader
URLClassLoader(urls,
loader)
return url_loader
Fundamental
programming concepts, including statements, expressions,
except Exception,
exception:
global errorinterpreters, and compilers
error =Python
exception
basics, including operators, string formatting, namespaces, classes, errors,
print "Unable
to create class loader"
and exceptions

Summary

Object-oriented programming concepts

File input/output
In this chapter, we covered applets, which are components that execute within a browser. To run Jython code as
an applet, you have to compile
it to intrinsic
a Java class.
You should also put it in a jar file to make downloading easier.
Python's
functions
We extended our address book
application
to work
an applet. We
also covered the inner workings of
Formatting,
parsing,
and as
manipulating
strings
AppletBrowser, which creates Jython applets through a context (AppletContext) and a stub
(AppletStub).
Interfacing with the Java APIs and working with Java Streams

Using Python and Java Swing to create GUIs

CONTENTS

Working with SQL and JDBC(TM)


Python and Java applets
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
CONTENTS
Web and Enterprise Applications with Jython
By Richard Hightower

Appendix A. Publisher:
Installing
Jython on Windows
Addison Wesley
Pub Date: June 28, 2002

Installing Java Runtime


ISBN: 0-201-61616-5
Table of
Installing the J2SEStep
Pages: 640by Step
Contents
Installing Jython

Characterized by ease of use, richness of expression, and concise syntax, Python has
First we'll install J2SE
v.1.4, because
it'sprogramming
the most recent
versionfor
available
as I awrite.
Then
install
remained
a premier
language
more than
decade,
andwe'll
is used
by the latest
version of Jython. novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
Before we start, let'sapplication
get something
straight. You might very well have trouble installing Jython because of the
development.
number of steps involved. You may need an expert computer configurator to help you with your Jython
installation. This might
a computer
or programmer,
might of
even
be that
kid next doorUsing
who's
Thisbetutorial
beginstechnician
with coverage
of some ofor
theit basics
Python
programming.
always making bootleg
floppies
so he can play
the latest
plenty
of skill-building
exercises
andgames.
interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
If your local expert fails
you, visit
theexperienced
newsgroupsprogrammers,
for Java and Python.
usuallyPython's
willing tobreadth
help new
techniques.
For
the bookThey're
demonstrates
of
programmers. Just check
out theand
newsgroup's
questions)
firstAPIs
to avoid
looking stupid.
capabilities
shows theFAQs
ways (frequently
that Python asked
interfaces
with Java
for professional
application development.

Installing Java
Runtime
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
Before you can use the Jython interactive interpreter, you need a Java development tool or Java runtime
environment. The Java Developers Kit (J2SE) is free and, as the reference implementation for Java, is the logical
Fundamental
programming
including
expressions,
choice, especially for beginners
(all of the
examples in concepts,
the book use
Jythonstatements,
in conjunction
with the J2SE). The
interpreters,
and compilers
J2SE's latest version is available
at the Javasoft
Web site.
Python
basics,
operators,
formatting,
namespaces,
classes,
errors,
Even though I use the J2SE,
I should
say including
that Microsoft's
free string
Java Virtual
Machine
(JVM) has
some features
and exceptions
that make it a good alternative
with Windows. In particular, it streamlines the installation of Java packages and
allows integration with ActiveX and Windows API via JDirect. Visit Microsoft's Web site for downloading
Object-oriented programming concepts
instructions.
input/output
One more thing before we File
get started.
All of the examples in the book were created on a Microsoft Windows 98
system, and the references are specific to Windows 98 users (although they should work equally well with
Python's
intrinsic
functions
Windows 95 and sometimes
Windows
NT v.4.0).
I chose Windows primarily because I'm a recovering
Microsoft lackey but also because it would be impossible to document J2SE and Python set up on all of the
Formatting, parsing, and manipulating strings
systems for which they're available. I had to choose something, and Windows was it.
Interfacing with the Java APIs and working with Java Streams
I will, however, show you Jython configuration and installation on Linux systems. I figure that if you have a
UNIX/Linux background, you're
to translate
DOS
to UNIX (or, for that matter, from DOS to
Using smart
Pythonenough
and Java
Swing tofrom
create
GUIs
Mac).
Working with SQL and JDBC(TM)
If you're not a Windows or Linux user, go to the platform.html page at the Python Web site (www.jython.org) for
JVM installation instructions.
Check
theapplets
links to pages specific to your platform.
Python
andout
Java
In addition, the book contains instructions for downloading and installing the Python
Installing the
J2SEStep by Step
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Before you can start installation, you need to download and install J2SE v.1.4 (or the equivalent for your
environment; Linux Whether
users, seeyou
Appendix
B). Just follow
the instructions
at http://java.sun.com/products/jdk/1.4/.
are a sophisticated
computer
user new to
programming or a serious
This can take a whileapplication
dependingdeveloper,
on your modem's
Once you
have
J2SE, install
software
by
Python speed.
Programming
with
thethe
Java(TM)
Classthe
Libraries
will
double-clicking the file
theinsight
directory
it to. and the know-how to put it to work.
giveinyou
intoyou
thedownloaded
power of Python
During setup, accept all defaults. For example, the default directory is C:\j2skd1.4.0. The rest of the instructions
assume that you've put the file there.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

If the J2SE Won't Start

Publisher:
Wesley
Be sure you saved
it with anAddison
*.exe file
extension, which tells Windows that the file is binary
Pub Date: June 28, 2002
executable.
ISBN: 0-201-61616-5

Table of
Contents
Startup

Pages: 640

Characterized by ease of use, richness of expression, and concise syntax, Python has
Once installation is complete,
your c:\autoexec.bat
file withfor
your
textthan
editor.
This file
usually
hasbyWindows
remained edit
a premier
programming language
more
a decade,
and
is used
and DOS startup information.
Make
sure that the
PATH
environment
variable
contains to
theJava(TM)
J2SE1.4 bin
novices and
professionals
alike.
In particular,
its close
relationship
makes
directory. Windows the
usestwo
PATH
to find executable
programs.
It gives
youfor
convenient
to Java,
the Java
languages,
when used in
combination,
ideal
Web and access
distributed
enterprise
interpreter, Javac, theapplication
Java compiler,
and other Java tools, which will come in handy as you do the exercises.
development.
For Windows 95, Windows
98, and
Windows
ME, addofthe
CLASSPATH
variable to autoexec.bat
This tutorial
begins
with coverage
some
of the basicsenvironment
of Python programming.
Using
after the PATH statement.
This
tells
Java,
the
interpreter,
and
Javac
where
to
find
Java
classes.
plenty of skill-building exercises and interactive programming sessions, this book will

help those new to programming develop an understanding of concepts and practical

REM *********techniques.
settings
for J2SE *****************
For experienced programmers, the book demonstrates Python's breadth of
SET PATH=%PATH%;C:\j2se1.3\bin;
capabilities and shows the ways that Python interfaces with Java APIs for professional
SET CLASSPATH=.
application development.
Notice that CLASSPATH is set to '.', which means the current directory. If there's already a CLASSPATH
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
statement, make sureand
a period
is specified.
Enterprise
Applications with Jython covers important topics such as:
For Windows NT4.0:

Fundamental programming concepts, including statements, expressions,


Go to the Start menuinterpreters,
and then theand
Settings
menu. Select Control Panel.
compilers
In the control panel, double-click the System icon.
In the Systems Option
dialogbasics,
box, choose
theoperators,
Environment
tab.formatting, namespaces, classes, errors,
Python
including
string
Edit the PATH environment
variable by adding C:\j2skd1.4.0\bin to the search path.
and exceptions
Use the same technique to edit the CLASSPATH variable.
Object-oriented programming concepts
For Windows 2000:
File input/output
1. Go to the Start menu and then the Settings menu; Select Control Panel.
2. In the control panel, Python's
double-click
the System
icon.
intrinsic
functions
3. In the Systems Properties dialog box, choose the Advanced tab.
parsing, and
manipulating
4. In the Advanced tab,Formatting,
hit the Environment
Variables
button. strings
5. Edit the PATH environmental variable by adding C:\j2skd1.4.0\bin to the search path.
Interfacing
withCLASSPATH
the Java APIsvariable.
and working with Java Streams
6. Use the same technique
to edit the
1.
2.
3.
4.
5.

Using Python and Java Swing to create GUIs


Working with SQL and JDBC(TM)

A Little Tip

Python and Java applets


Before you add the directory to the PATH statement, make sure there are no older versions of the
addition,
theare,
book
contains
instructions
forofdownloading
J2SE already In
there.
If there
they'll
be executed
instead
C:\j2se\1.3. and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
samples
make this book
a useful
learning
experience.
Once you've installedand
thenumerous
J2SE andcode
edited
the autoexec.bat
file, reboot
your
PC. Then,
to test that everything is
okay, go to the DOS prompt, and enter java version at the command line. You should see the
Whether you are a sophisticated computer user new to programming or a serious
following:
application developer, Python Programming with the Java(TM) Class Libraries will
give you
insight into the power of Python and the know-how to put it to work.
c:\java-version
"1.3.0"

Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.0-b92)


Java HotSpot(TM) Client VM (build 1.4.0-b92, mixed mode)

777

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

Troubleshooting

Publisher:
Addison
Wesley
If you don't see the okay
message,
type c:\j2skd1.4.0\bin\java
at the DOS prompt.
Pub Date: June 28, 2002

C:\> c:\j2sjd1.4.0\bin\java
-version
ISBN: 0-201-61616-5
Table
of
java
version
"1.3.0"

Pages: 640
Contents
Java(TM)
2 Runtime Environment, Standard Edition (build 1.4.0-b92)
Java HotSpot(TM)
Client
(build
mode)Python has
Characterized
by easeVM
of use,
richness1.4.0-b92,
of expression, andmixed
concise syntax,
remained a premier programming language for more than a decade, and is used by
If this works, you have a problem with your PATH statement. Try entering PATH at the command line to
novices and professionals alike. In particular, its close relationship to Java(TM) makes
see what it looks like.
Probably
you have
a typo
forgot to reboot
(autoexec.bat
runs only enterprise
after
the two
languages,
when
usedor
inyou
combination,
ideal for
Web and distributed
rebooting).
application development.
If you still don't see
thetutorial
okay message
and all
you're getting
"Bad
or filename,"
then your
setup
This
begins with
coverage
of someis of
the command
basics of Python
programming.
Using
program didn't work.
You
may
have
put
the
J2SE
in
the
wrong
directory.
Go
to
the
Start
menu
and
then
plenty of skill-building exercises and interactive programming sessions, this book will
Find Files or Folders,
look
fortojava.exe.
This should
tellanyou
where you installed
the J2SE
or if you
helpand
those
new
programming
develop
understanding
of concepts
and practical
actually installed it.techniques.
If all else fails,
it's
time
to
call
in
an
expert
configurator.
For experienced programmers, the book demonstrates Python's breadth of

capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.

Installing Jython

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
Jython is free and open
All you
have to dowith
is go
to http://www.jython.org/download.html
and do what
andsource.
Enterprise
Applications
Jython
covers important topics such as:
you're told. (Jython is the latest Python release.)
Fundamental
programming
Jython is backward compatible
with JPython
(in whichconcepts,
all of the including
examples statements,
are written),expressions,
so feel free to use it. Just
and compilers
make sure to type jythoninterpreters,
instead of jython
in the interpreter and jythonc instead of jythonc in the
compiler.
Python basics, including operators, string formatting, namespaces, classes, errors,
exceptions
To install Jython, go to theand
directory
where it's downloaded and type java jython-20 at the DOS prompt.
Object-oriented programming concepts
C:\temp> java jython-20
input/output
Note that a Java class nameFile
does
not end with a .class extension, so leave it off.
Python's read
intrinsic
functions
While the setup program executes,
and accept
the license agreement.

Startup

Formatting, parsing, and manipulating strings

Interfacing with the Java APIs and working with Java Streams
Once the setup is complete, edit the autoexec.bat file to access the Jython interpreter. Open the file with a text
Using
and Java
Swing
editor, and add the following
linesPython
after those
entered
for to
thecreate
J2SE.GUIs
For Jython:

Working with SQL and JDBC(TM)

REM ********* settings


Jython *****************
Python andfor
Java applets
SET PATH=%PATH%;C:\Jython
In addition, the book contains instructions for downloading and installing the Python
SET CLASSPATH=%CLASSPATH%;C:\Jython.jar
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
ThePATH statementand
tellsnumerous
Windowscode
to append
c:\Jython
to the
PATH
environment
variable, which holds the
samples
make this
book
a useful
learning experience.
file's executable search path for Windows. The CLASSPATH statement enables the Java interpreter to find the
Jython class libraries.Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
At this point you should
to run
Jython
by entering
Jython
atknow-how
the command-line
prompt. More
give be
youable
insight
into
the power
of Python
and the
to put itDOS
to work.
installation information is available at www.jython.org/installhtml.

777

Jython doesn't come with all of the standard Python modules, but you can download them from
www.jython.org/download.html and follow the installation instructions.

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

Installation Tip

Publisher:with
Addison
Wesley report them to jython-dev@lists.sourceIf you have any problems
installation,
Pub Date:
2002
forge.net. (Tell
them IJune
sent28,
you.)
Make sure you've done everything you can before reporting
ISBN:
0-201-61616-5
what
might
turn
out
to
be
a
nonproblem.
You may discover that your problem is unique to your
Table of
Pages:
640
platform. To find out for sure, go to www.jython.org/platform.html. They'll let you know.
Contents

Characterized
of use,that
richness
and file,
concise
has
To run your downloaded
file, go toby
theease
directory
holds of
theexpression,
Python library
and syntax,
run thisPython
at the command
remained
a
premier
programming
language
for
more
than
a
decade,
and
is
used
by
line:
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two
languages,
when used in combination, ideal for Web and distributed enterprise
C:\temp> jython
-jar
pylib152a.jar
application development.
Done at last. If you've come this far, you can call yourself a master configurator. Nothing can stop you from
This tutorial begins with coverage of some of the basics of Python programming. Using
learning Python.
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
CONTENTS
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
Object-oriented programming concepts
File input/output
Python's intrinsic functions
Formatting, parsing, and manipulating strings
Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs
Working with SQL and JDBC(TM)
Python and Java applets
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
CONTENTS
Web and Enterprise Applications with Jython
By Richard Hightower

Appendix B. Publisher:
Installing
Jython on Linux
Addison Wesley
Pub Date: June 28, 2002

Unpacking the Blackdown


Package
ISBN: 0-201-61616-5
Table of
Unpacking the Sun
Package
Pages:
640
Contents
Installing the Sun and Blackdown Distributions
Characterized
by ease of use, richness of expression, and concise syntax, Python has
Installing Older
Distributions
remained a premier programming language for more than a decade, and is used by
Running Jython

novices and professionals alike. In particular, its close relationship to Java(TM) makes
Jaysen Lorenzen the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
To illustrate the installation of Jython on Linux, we're using the most recent version of the SDK1.3 glibc.
tutorial begins
with
coverage
of someusing
of thethe
basics
Python (such
programming.
Using
Versions 1.2 and 1.3This
are available
only for
newer
distributions
libc6oflibraries
as Red Hat
v.5.x
plenty
of
skill-building
exercises
and
interactive
programming
sessions,
this
book
will
and Debian v.2.x). The libc5 versions of J2SE v.1.1x are available on the Blackdown site for those of you
help those new to programming develop an understanding of concepts and practical
running older distributions.
techniques. For experienced programmers, the book demonstrates Python's breadth of
and system,
shows the
Python
interfaces
Java APIs
for"superuser"
professional(that
If you're the root usercapabilities
of your Linux
logways
in asthat
root
, or use
the su with
command
to gain
application
is, root) privileges before
trying development.
each install. If you're not the root user, you can install software only to your own
user directory/home/<your name>or to directories for which you have read, write, and execute access. (If
Programming
Java(TM)
Class
Tutorialadministrator
for Building for
Web
you want to install onPython
a machine
other thanwith
yourthe
own,
you may
haveLibraries:
to ask yourA system
help.)
and Enterprise Applications with Jython covers important topics such as:
The first step in your Linux Jython install is downloading the J2SE (v.1.3) from Blackdown
(http://www.blackdown.org), from which you'll get a compressed tar ball, or Sun Microsystems
Fundamental programming concepts, including statements, expressions,
(http://java.sun.com), from which you'll get a self-extracting package. The next step is unpacking the J2SE and
interpreters, and compilers
installing it.

Unpacking the

Python basics, including operators, string formatting, namespaces, classes, errors,


and exceptions
Blackdown
Package

Object-oriented programming concepts


Many, many versions of the J2SE are available from Blackdown. I chose the latest, j2sdk1.3 (j2sdk-1.3.0-RC1linux-i386.tarbz2). Only a bziped
package is offered for this release, but earlier releases come with standard
File input/output
gziped packages.
Python's intrinsic functions
In a shell, as the root, or using the su command, copy or move the downloaded file to a directory. This directory
can be any one you want, but
/usr/local/lib
is theand
best
choice because
it makes it easier for other users to find
Formatting,
parsing,
manipulating
strings
examples and documentation. (Thus, the J2SE subdirectory is /usr/local/lib/j2sdk1.x). Then unzip and untar the
Interfacing
with the
Java
and working with Java Streams
file by changing the directory
to its location
with
theAPIs
command
Using Python and Java Swing to create GUIs | tar -xvfbzip2 -dc j2sdk-1.3.0-RC1-linux-i386.tar.bz2
SQLbzip2
and JDBC(TM)
If you downloaded a gzipedWorking
package,with
replace
with gzip in the command.
Python and Java applets
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

HotSpotClient

Publisher:
Wesley
The default virtual
machineAddison
for J2SDK
v.1.3 is HotSpotClient. If it doesn't work well with Jython,
Pubthe
Date:
change it by editing
file.June 28, 2002

ISBN: 0-201-61616-5
Table
of
/<jdk1.x>/jre/lib/jvm.cfg
Pages: 640
Contents

(where <jdk1.x>
is the jdk install
directory)
Characterized
by ease
of use, richness of expression, and concise syntax, Python has

remained a to
premier
programming
language
for more
than a decade,
is used by
Moving"-classic"
the first
line of the file
will change
the default
to Linuxand
Native
novices and professionals alike. In particular, its close relationship to Java(TM) makes
Threads.
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.

Unpacking the
Sun Package
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
Here we're using J2SDK
v.1.3 and
self-extractingdevelop
binary package
(j2sdk-1_3_0-linux.bin).
a shell, as the
help those
newthe
to programming
an understanding
of concepts andInpractical
root, or using the sutechniques.
command, For
copyexperienced
or move theprogrammers,
downloaded the
file book
to thedemonstrates
directory of your
choiceagain
Python's
breadth of we're
usinguser/local/lib, so
the J2SE and
subdirectory
/user/local/lib/jdk.1.x.
capabilities
shows theis ways
that Python interfaces with Java APIs for professional
application development.
Make the file executable with the command
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

chmod a+x j2sdk-1_3_0-linux.bin


Execute it with the command

Fundamental programming concepts, including statements, expressions,


interpreters, and compilers

./j2sdk-1_3_0-linux.bin

This launches a script and displays the license agreement from Sun (which you must read and accept). The script
Python basics, including operators, string formatting, namespaces, classes, errors,
unpacks and installs the SDK.
and exceptions

Object-oriented
programming concepts
Installing the Sun
and Blackdown
Distributions
File input/output
The installation procedures that follow are common to both Sun and Blackdown.
Python's intrinsic functions
First we have to set some environment variables. There are several ways to do this, all of which depend on user
rights and preferences.
Formatting, parsing, and manipulating strings
InterfacingVariables
with the Java APIs and working with Java Streams
Setting the Environment
Using Python and Java Swing to create GUIs
To set PATH and CLASSPATH, edit the rc file in your home directory for the shell you're using. I've chosen the
bash shell, so the file to editWorking
is ~/.bashrc.
If a PATH
statement exists, add the following line just below
with SQL
and JDBC(TM)
PATH=etc/etc.
Python and Java applets

PATH=$PATH:/<jdk1.x>/bin

In addition, the book contains instructions for downloading and installing the Python
where<jdk1.x> is
the J2SE
directory,
the complete
pathTerminology,
created in the
previous steps.
If there are
language
and
the Javaincluding
Development
Kit (JDK).
definitions,
explanations,
any references to older
J2SE
versions
here,
remove
them.
You
should
see
and numerous code samples make this book a useful learning experience.

PATH=$PATH:/usr/local/lib/j2sdk1.3/bin
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
If there's no CLASSPATH statement, add it. If there is one, add the following line after it:
give you insight into the power of Python and the know-how to put it to work.

CLASSPATH=/<jdk1.x>/lib/tools.jar:./

777

where<jdk1.x> is the J2SE directory, including the complete path created during the previous steps.

Remove any references


to older
J2SE versions
in the
YouClass
should
see
Python
Programming
with
thepath.
Java
Libraries:
A Tutorial for Building
Web and Enterprise Applications with Jython

CLASSPATH=/usr/local/lib/j2sdk1.3/lib/tools.jar:./
By Richard Hightower
If you don't see a CLASSPATH statement, add either the PATH=$PATH or the CLASSPATH line shown
Publisher: Addison Wesley
above. If you see an export statement, append a space, the word PATH, another space, and the word
Pub Date: June 28, 2002
CLASSPATH to it. If you
don't see an export statement, create one containing PATH and CLASSPATH at
ISBN: 0-201-61616-5
the bottom
of
the
file.
Table of

Pages: 640

Contents

export PATH CLASSPATH


Characterized by ease of use, richness of expression, and concise syntax, Python has
Now you should have
these PATH
,CLASSPATH
, andlanguage
exportforlines:
remained
a premier
programming
more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
PATH=$PATH:/usr/local/lib/j2sdk1.3/bin
the two languages, when used in combination, ideal for Web and distributed enterprise
CLASSPATH=/usr/local/lib/j2sdk1.3/lib/tools.jar:./
application development.

export TERM PATH CLASSPATH


This tutorial begins with coverage of some of the basics of Python programming. Using
Save and close the file.
Then
the exercises
shell you're
in soprogramming
that the environment
take
plenty
of re-execute
skill-building
andworking
interactive
sessions,changes
this bookwill
will
effect.
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
If the computer you're
on is yoursand
or shows
if your the
system
is by your with
side,Java
you can
PATH and
capabilities
waysadministrator
that Python interfaces
APIssetfortheprofessional
CLASSPATH variables
globally
as
root
(regardless
of
the
shell
used)
by
editing
the
/etc/profile
file and
application development.
making the same changes as for the bash shell.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise
Applications with Jython covers important topics such as:
Installing Older
Distributions
If you're downloading a J2SE
version older
than 1.2, you'll
have to
get the JFC/Swing
from the JavaSoft
Fundamental
programming
concepts,
including
statements, classes
expressions,
site (http://java.sun.com/products/jfc/#download-swing).
Make
sure
your
J2SE
and
JFC
versions
matchfor
interpreters, and compilers
example, if you have J2SE v.1.1.7, you need Swing v.1.1.1 (swing1_1_1.tar.Z).
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions

Object-oriented programming
concepts
Tar/Zip
File input/output
The download page doesn't mention Linux, so choose the standard tar or zip file, not the installer.
Python's intrinsic functions
In a shell, as root, or with the su command, copy or move the downloaded file to the directory you choose. As
Formatting,
parsing,
andswing-1.1.x
manipulating
strings(/usr/local/lib/jdk1.1.7/swing-1.1.x), so
before, we're using /usr/local/lib
and we
want the
directory
we move the file to /usr/local/lib/jdk1.1.7/. Installing the Swing classes in the J2SE directory makes it easy for
Interfacing
with the Java APIs and working with Java Streams
all users to find the examples
and the documentation.
Using Python
and Java the
Swing
to create
GUIs
Unzip and untar the downloaded
file by changing
directory
to its
location (/usr/local/lib/jdk117_vla) with the
command
Working with SQL and JDBC(TM)

gzip -dc swing1_1_1.tar.Z | tar -xvfPython and Java applets

which creates the Swing subdirectory.


In addition, the book contains instructions for downloading and installing the Python
language
and the Java Development
Kit (JDK).
definitions,
Add the swing.jar file
to the CLASSPATH
variable by modifying
theTerminology,
CLASSPATH
line in theexplanations,
personal
and
numerous
code
samples
make
this
book
a
useful
learning
experience.
~/.bashrc file or the global /etc/profile file.

Whether you are a sophisticated


computer user path
new to programming
or a serious
CLASSPATH=$CLASSPATH:/<base
path>/<swing
>/swing.jar
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight
into theispower
of Python
the know-how
toinstalled
put it to work.
/<base path>/<swing
path>/
the complete
pathand
to swing.jar.
If you
J2SE v.1.1.7, the
path should look like

777

CLASSPATH=$CLASSPATH:/jdk117_v1a/swing-1.1.1fcs/swing.jar

Save and close the file.


You'llProgramming
have to restartwith
the shell
the environment
changes
just made
toBuilding
take effect.
Python
the for
Java
Class Libraries:
A Tutorial
for
Web and Enterprise Applications with Jython
By Richard Hightower

Installation Alternatives

Publisher: Addison Wesley


Pub Date: June 28, 2002

There are countless ways


install the J2SE on Linux. For distributions using RPM package
ISBN:to0-201-61616-5
Table
of
managers
(like
those
here),
RPM

Pages: 640 and DEB packages are available, which you can find on the
Contents
Linux distribution FTP site.
Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
Testing the Installation
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
Test your install by starting a shell and entering java version. You should get a message like this:
application development.

[jaysonl@r_monkey
lib]$ java -version
This tutorial begins with coverage of some of the basics of Python programming. Using
java version plenty
"1.3.0"
of skill-building exercises and interactive programming sessions, this book will
Java(TM) 2 Runtime
Environment, Standard Edition (build Blackdown-1.3.0-RC1)
help those new to programming develop an understanding of concepts and practical
Classic VM (build
Blackdown-1.3.0-RC1,
native threads, sunwjit)
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
If you don't, there may be something wrong. Try entering the complete path to the Java executable, which in our
application development.
case is
Python Programming
with the Java(TM) Class Libraries: A Tutorial for
Building Web
[jaysonl@r_monkey
/]$ /usr/local/lib/j2sdk1.3/bin/java
-version
and Enterprise Applications with Jython covers important topics such as:

The appropriate response means that you have a problem with your environment variables. Check the rc file for
your shell or the /etc/profileFundamental
file to makeprogramming
sure the pathsconcepts,
are correct.
(Remember,
you have
to re-execute the shell
including
statements,
expressions,
for the changes to take effect.)
interpreters, and compilers
If you get a "SegmentationPython
Fault" message,
chances operators,
are you installed
the wrong binary
releaseclasses,
of the J2SE.
basics, including
string formatting,
namespaces,
errors,If
you're using an older Linuxand
distribution
(older
than
Red
Hat
v.5.x
or
Debian
v.2.x)
and
chose
the
glibc
binary,
exceptions
you may find you need libc5 instead. Check your Linux distribution references for the correct library type.
Object-oriented programming concepts
If the virtual machine displays "Font specified in font.properties not found," edit the file:
File input/output

/<jdk1.x>/jre/lib/font.properties

Python's intrinsic functions


where<jdk1.x.> is the J2SE install directory. Comment out the fonts that weren't found to stop these
warning messages. Installing
the fonts is
an alternative
solution. strings
Formatting,
parsing,
and manipulating
If none of these quick fixesInterfacing
does the trick,
a problem.
Refer towith
the Blackdown
withyou
the have
Java APIs
and working
Java Streamsinstallation FAQ page
(http://www.blackdown.org/java-linux/docs/faq/FAQ-java-linux.html#toc4) for advice.
Using Python and Java Swing to create GUIs

Downloading the Jython and CPython Libraries


Working with SQL and JDBC(TM)

If all went well with the installation,


canapplets
download the Jython and the CPython libraries from
Python andyou
Java
http://www.jython.org or http://www.python.org. Then, in a shell, as root, or using the su command, change the
directory to which you
downloaded
class
file byinstructions
entering for downloading and installing the Python
In addition,
the the
book
contains
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
java Jython1xand numerous code samples make this book a useful learning experience.
where1x is the number
of theyou
downloaded
Jython version.
Whether
are a sophisticated
computer user new to programming or a serious

application developer, Python Programming with the Java(TM) Class Libraries will
In our case, the command looks like
give you insight into the power of Python and the know-how to put it to work.

java Jython11

777

This launches the java GUI version of the install shield and walks you through a series of questions. One
question is which directory you want to install Python in. The default is your home directory if you've logged in

as root. (Once again,Python


althoughProgramming
you can choose
anythe
directory
I recommend
/usr/local/lib.).
The
is the
with
Java
Class Libraries:
A Tutorial
forresult
Building
creation of a directory
called
in Applications
the directory specified.
To install Jython, replace the Jython11
Web
andJython-1.x
Enterprise
with Jython
install class with its Jython
counterpart.
By Richard
Hightower
The next step is to edit your
environment
Publisher:
Addisonvariables
Wesley (here, in the ~/.bashrc file) by adding the following just
below the existing PATH statement:
Pub Date: June 28, 2002

ISBN: 0-201-61616-5
PATH=$PATH:/<Jython-1x>
Table of

Contents

Pages: 640

where<Jython-1x> is your chosen directory and the number of the Jython version you've downloaded.
Here's the actual line:Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
PATH=$PATH:/usr/local/lib/Jython-1.1
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
Now add the following
CLASSPATH
line just below the existing one:
application
development.

CLASSPATH=$CLASSPATH:/<Jython-1.x>/Jython.jar
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
where<Jython is help
the installation
and -1.x>
is the
version of
installedin
ourpractical
case,
those new directory
to programming
develop
an Jython
understanding
concepts and
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application
Save and close the file,
and thendevelopment.
restart your shell so the changes take effect.

CLASSPATH=$CLASSPATH:/usr/local/lib/Jython-1.1/Jython.jar

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

If It's Your First Time


Fundamental programming concepts, including statements, expressions,
To start Jython for the
first time,and
youcompilers
need to be the root user or use the su command (to gain
interpreters,
superuser privileges). The first run creates some new directories and searches your path to find the
J2SE-installed Java Python
classes.basics, including operators, string formatting, namespaces, classes, errors,
and exceptions

Running JythonObject-oriented programming concepts


File input/output
To run Jython for the first time, type Jython at the prompt, and press Enter. You should see something like
this:
Python's intrinsic functions

packageManager: processing
new
Formatting, parsing,
andjar,"/usr/local/lib/Jython-1.1/jython.jar"
manipulating strings
packageManager: processing new jar,"/usr/local/lib/j2sdk1.3/lib/tools.jar"
packageManager: processing
new
Interfacing with the
Javajar,"/usr/local/lib/j2sdk1.3/jre/lib/rt.jar"
APIs and working with Java Streams
packageManager: processing new jar,"/usr/local/lib/j2sdk1.3/jre/lib/i18n.jar"
Using Python andnew
Java Swing
packageManager: processing
jar,to create GUIs
"/usr/local/lib/j2sdk1.3/jre/lib/sunrsasign.jar"
Working with(JIT:
SQL andsunwjit)
JDBC(TM)
Jython 1.1 on java1.3.0
Copyright (C) 1997-1999 Corporation for National Research Initiatives
Python and Java applets

Then press Ctrl-D to exit interactive mode.


In addition, the book contains instructions for downloading and installing the Python
language
the Java
Development
(JDK).
Terminology,
definitions,
If you want to use parts
of the and
standard
Python
library thatKit
aren't
included
with Jython,
you haveexplanations,
two choices.
and
numerous
code
samples
make
this
book
a
useful
learning
experience.
You can download and install them from the Jython download page (recommended by the folks at the Jython site
because the Python v.1.5.2 libs version has been modified to work better with Jython):
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
http://www.jython.org/download.html#pylib
give you insight into the power of Python and the know-how to put it to work.
or you can add a pointer in python.path to the lib directory of a CPython distribution (try this with your
system administrator by your side).

777

In a shell, as root, or using su, change the directory to the one you downloaded the CPython class file to, and

enter

jython -jar

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
pylib152e.jar
By Richard Hightower

There will be a flurry of activity on the screen as the CPython libraries are extracted, copied, and compiled to
Publisher: Addison Wesley
your directories. Your installation is now complete.
Pub Date: June 28, 2002

Table of
Contents

ISBN: 0-201-61616-5
Pages: 640

CONTENTS

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
Object-oriented programming concepts
File input/output
Python's intrinsic functions
Formatting, parsing, and manipulating strings
Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs
Working with SQL and JDBC(TM)
Python and Java applets
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
CONTENTS
Web and Enterprise Applications with Jython
By Richard Hightower

Appendix C. Publisher:
The Power
of Scripting
Addison Wesley
Pub Date: June 28, 2002

Scripting Versus Programming


Languages
ISBN: 0-201-61616-5
Table of
Java and Scripting
Pages: 640
Contents
Integrating Scripting with Jython
Characterized
by ease
of use, richness of expression, and concise syntax, Python has
Which Scripting
Language
to Choose
remained a premier programming language for more than a decade, and is used by
Hello WorldThe Programming Rosetta Stone
novices and professionals alike. In particular, its close relationship to Java(TM) makes
What Does the
It All
twoMean?
languages, when used in combination, ideal for Web and distributed enterprise

application development.
Scripting languages are dynamic, interactive environments for rapid development of Java code. Many are either
object-oriented or object-based,
almost
are interpreted
late-bound
polymorphism.
This Using
makes
This tutorialand
begins
withallcoverage
of someand
of use
the basics
of Python
programming.
them extremely dynamic
and
easy
to
programessential
ingredients
in
rapid
application
development
(RAD),
plenty of skill-building exercises and interactive programming sessions, this book will
component gluing, and
helpproject
those prototyping.
new to programming develop an understanding of concepts and practical

Scripting

techniques. For experienced programmers, the book demonstrates Python's breadth of


capabilities
and shows the ways that
Python interfaces with Java APIs for professional
Versus
Programming
Languages
application development.

There's a fine line between scripting and programming languages. For example, Smalltalk is an extremely
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
dynamic interpreted language, but it's not for scripting. A true scripting language, unlike Smalltalk, must employ
and Enterprise Applications with Jython covers important topics such as:
late-bound polymorphism and dynamic typing.
Many UNIX programmers Fundamental
program in Cprogramming
and C++ and concepts,
glue modules
together
with higher-level
shell
including
statements,
expressions,
programming (Korn, Bourne,
C,
etc.).
Or
they
use
the
scripting
language
Tcl
for
both
programming
their GUIs
interpreters, and compilers
and gluing together their C++ classes and libraries. Another option is to use Python as the glue. It's often
preinstalled with UNIX systems
is easy
to extend
with C. string formatting, namespaces, classes, errors,
Pythonand
basics,
including
operators,
and exceptions
The most prevalent object-based scripting language is Visual Basic, which is often used to glue together COM
components written in different
languages. programming concepts
Object-oriented
Scripting languages don't replace
system languages but rather augment them in the following ways:
File input/output

Python's intrinsic functions


Extending applications
Formatting, parsing, and manipulating strings
Debugging
Interfacing with the Java APIs and working with Java Streams
Learning and experimenting with the Java API
Using Python and Java Swing to create GUIs
Rapid prototyping
Working with SQL and JDBC(TM)
Gluing subsystems and components
Python and Java applets
Automating general testing and regression testing
In addition, the book contains instructions for downloading and installing the Python
For information about
increasing
with scripting,
read John
Ousterhout's
online paper
Scripting:
language
andproductivity
the Java Development
Kit (JDK).
Terminology,
definitions,
explanations,
Higher Level Programming
for
the
21st
Century
(http://www.home.pacbell.net/ouster/scripting.html),
which
and numerous code samples make this book a useful learning experience.
notes a sharp productivity increase with scripting languageson the order of 5 to 10 times higher than with a
strongly typed language
like Java.
From
my own experience,
say new
theyto
areprogramming
2 to 3 times faster
depending on the
Whether
you are
a sophisticated
computerI'duser
or a serious
application.
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

Java and Scripting

777

I call Java a scripting language on steroids. In fact, because it uses statically typed polymorphism, it's more

precisely a hybrid. This


may at
first seem likewith
a disadvantage,
it turns
out thatA Java's
statically
typed
Python
Programming
the Java but
Class
Libraries:
Tutorial
for Building
polymorphism, as well
as its
design
by interface,
is great for
systems
programming, framework definition, and
Web
and
Enterprise
Applications
with
Jython
component development.
It would
be wrong to view Java as a system programming language by classical
By Richard
Hightower
definition. Rather, it's a virtual system programming language for a virtual systemthat is, a virtual machine (the
Java Virtual Machine). Publisher:
Like its scripting
language
Addison
Wesley cousins, it can be very dynamicnot as much as Python or
Smalltalk but certainly more
than
C++.
Pub Date: June 28, 2002
ISBN: 0-201-61616-5

Table
of
Java's
main drawback
for scripting is that it can't glue components together. What you need to do is build

Pages: 640
Contents
components
with Java and glue them together with a true scripting language.

by ease of APIs
use, richness
of expression,
concisescripting
syntax, Python
has
Java's class reflectionCharacterized
and bean introspection
make a great
basis for and
integrating
languages.
remained
a
premier
programming
language
for
more
than
a
decade,
and
is
used
by
Essentially, the scripting language can get metadata about a Java class, which it uses to change its properties,
professionals
alike.
In particular, its
close
relationship
toand
Java(TM)
makes
handle its events, andnovices
invokeand
its methods.
I have
metaprogrammed
with
COM,
CORBA,
Java, and
of the
the
two
languages,
when
used
in
combination,
ideal
for
Web
and
distributed
enterprise
three Java is my preference because of these features.
application development.
Some people think that the only language for the JVM is Java. They're wrong. Like many platforms (and the
tutorialthe
begins
coverage
some
of the basics
programming.
JVM is very much a This
platform),
virtualwith
machine
has of
many
languages,
and of
thePython
list keeps
growing. InUsing
particular,
plenty
of
skill-building
exercises
and
interactive
programming
sessions,
this book will
combining the JVM with scripting enhances rapid application development.
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
Integrating Scripting
withtheJython
capabilities and shows
ways that Python interfaces with Java APIs for professional
application development.
Jython is very close to Python and has been certified as 100 percent pure Java. In fact, in a recent Web poll
Python
with
the Java(TM)
Class
Libraries:
A Tutorial
for Building
Web
conducted by NetBeans
(theProgramming
Java IDE maker
bought
by Sun) on
integrating
a scripting
language
with its
Java
and
Enterprise
Applications
with
Jython
covers
important
topics
such
as:
IDE, Jython won by a landslide. It also won a similar poll on JDJ and the Java channel.
By the way, you can develop Java Server Pages in Jython. They're called Python Server Pages, and they run in a
Fundamental programming concepts, including statements, expressions,
Java servlet. They're also open source. (Find out more about them at http://www.ciobriefings.com.)
interpreters, and compilers

Tcl

Python basics, including operators, string formatting, namespaces, classes, errors,


and exceptions
The Java command language (Jacl) implements Tcl8.x for writing scripts for Java components and APIs.
Object-oriented
Another Tcl blend allows Java
objects to beprogramming
manipulated concepts
directly from Tcl. Because Tcl is the premier RAD
language, many Jacl users have claimed significant reduction in development costs with its use. (Find out more
File input/output
about Jacl at http://www.tcl.tk/software/java/.)
Python's intrinsic functions

JavaScript (Rhino)

Formatting, parsing, and manipulating strings


Rhino is an implementation of JavaScript v.1.5, a very powerful object-based language. Freely available and
Interfacing
with
the Java APIs
and workinginwith
Java Streams
open source, Rhino is a natural
for rapid
application
and prototyping
the JVM.
Using Python and Java Swing to create GUIs

Instant Basic

Working with SQL and JDBC(TM)


Halcyon's Instant Basic is a Visual Basic clone that allows quick porting of existing Visual Basic applications to
andcomponents,
Java appletsetc.). Its iASP, a clone of JSP, works with Java so that you
the Java platform (the IDE,Python
database
can use VBScript and JavaScript to access JavaBeans, CORBA, EJB, and so forth. Learn more about Instant
In addition, the book contains instructions for downloading and installing the Python
Basic at http://www.halcyonsoft.com.
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.

Java BeanShell

Whether you are a sophisticated computer user new to programming or a serious


application
developer,
Programming
withthat
the executes
Java(TM)Java
Class
Librariesand
will
BeanShell is interpreted
Java with
a syntax Python
very similar
to real Java's
statements
givescripting
you insight
into theit's
power
of Pythontyped
and so
themuch
know-how
putsyntax
it to work.
expressions. Like other
languages,
dynamically
of the to
Java
for type
declaration and casting is optional. BeanShell is great for writing prototypes and experimenting with unfamiliar
APIs. Also, it supports beans, it's very easy to use, and it's open source. To find out more about BeanShell, visit
http://www.Beanshell.org.

777

Smalltalk/Bistro
Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
Richard
Hightower
a SmalltalkBy
variant
with
extensions for Java features and integration.

Bistro is
It offers software developers the
ability to code in a readable and expressive syntax. Although it's dynamically typed, it has the option of static
Publisher: which
Addison
Wesley
typing for closer Java integration,
means
that you can mix and match statically and dynamically typed
Pub
Date:
28, 2002
systems. Bistro combines
Java
typeJune
safeness
with Smalltalk fast development.
Table of
Scheme/Skij
Contents

ISBN: 0-201-61616-5
Pages: 640

Characterized by ease of use, richness of expression, and concise syntax, Python has
Skij is a small Scheme interpreter implemented in Java. A variant of Lisp, it enables rapid prototyping in the
remained a premier programming language for more than a decade, and is used by
Java environment and has many advanced features such as macros and first class continuations. There are at least
novices and professionals alike. In particular, its close relationship to Java(TM) makes
15 Scheme ports to the JVM.
the two languages, when used in combination, ideal for Web and distributed enterprise
development.
You can download aapplication
copy of Skij
at http://www.alphaworks.ibm.com/tech/skij. If it's not your favorite Java
Scheme variant, let me know why.
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced
programmers,
the book demonstrates Python's breadth of
Need
More?
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
If I didn't mention your favorite language, or the if the ones I covered don't tickle your fancy, see
Robert Tolksdorf's
ofthe
JVM
programming
languages.A Tutorial for Building Web
Pythoncomprehensive
Programminglist
with
Java(TM)
Class Libraries:

and Enterprise Applications with Jython covers important topics such as:
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers

Dynamic
to Static Typing and Back
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
BeanShell is essentially a Java variant with dynamic and optional static typing. Bistro is a
Smalltalk variant with
static and optional
dynamic concepts
typing. Both languages are on the right track,
Object-oriented
programming
given that Visual Basic, the granddaddy of all scripting languages, provides both static and
File input/output
dynamic typing support.
Python's intrinsic functions

Which Scripting Language to Choose

Formatting, parsing, and manipulating strings

In choosing a scripting language,


ease with
of usetheisJava
a primary
criterion.
Forwith
example,
a language may be easy to learn
Interfacing
APIs and
working
Java Streams
because it resembles another language that most developers know. Or it may just have an easily grasped syntax.
Using Python and Java Swing to create GUIs
A particular benefit of scripting languages is that they can be embedded in a large application to make it more
extensible. The question is Working
how embeddable
particular
language is and how well it integrates with Java.
with SQLa and
JDBC(TM)
Resemblance to the parent Python
language
important
andisJava
appletsbecause it can affect how code ports from a legacy system (i.e.,
non-Java). The degree of resemblance can influence how quickly developers can get up to speed.
In addition, the book contains instructions for downloading and installing the Python
A language's unique language
features might
beJava
thoseDevelopment
that gear it toKit
a particular
problem domain.
For example,
does it
and the
(JDK). Terminology,
definitions,
explanations,
have a library for generating
XML code
and HTML
documents?
Is it easy
to integrate
JSP (making it particularly
and numerous
samples
make this book
a useful
learningwith
experience.
suitable for Web programming)?
Whether you are a sophisticated computer user new to programming or a serious
Some languages excel
at common
tasks likePython
string Programming
parsing; some with
don't.the Java(TM) Class Libraries will
application
developer,
give you insight into the power of Python and the know-how to put it to work.
A certain scripting language may be better than Java at tasks like manipulating strings and collections. Features
such as extensive class libraries and useful built-in language constructs enhance programming productivity.

777

A key criterion is a language's ease of integration with Java classes and APIs. For example, a language that
permits its classes to subclass Java classes has good integration. So does a language that allows methods to have

type signatures.

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
scripting languages
are better
than others at code debugging. Some have a more pleasant development
By Richard
Hightower

Some
environment.

Publisher: Addison Wesley


Pub Date:
June 28, 2002
Hello WorldThe
Programming
Rosetta Stone
Table of
give
you a feel
Contents

ISBN: 0-201-61616-5
Pages:
640going
scripting,
we're

To
for
to compare how it's done in three languages, Java, JavaScript, and
Python. We'll make the comparison more interesting by adding a Say Hello button, which when pressed causes a
Characterized
by World"
ease of use,
richnessbold
of expression,
and concise syntax, Python has
window to pop up and
display "Hello
in 18-point
type.
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
The Java Version
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.

import javax.swing.*;
import java.awt.Font;
This tutorial begins with coverage of some of the basics of Python programming. Using
import java.awt.event.*;
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical

class MyFrametechniques.
extends
For JFrame{
experienced programmers, the book demonstrates Python's breadth of
public MyFrame(){
capabilities and shows the ways that Python interfaces with Java APIs for professional
JButtonapplication
sayHello;
development.
sayHello = new JButton("say hello");
sayHello.setMnemonic('h');
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
this.getContentPane().add(sayHello);
and Enterprise Applications with Jython covers important topics such as:
this.setVisible(true);
this.pack();
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
sayHello.addActionListener(new
ActionListener(){

public void actionPerformed(ActionEvent ae){


Python basics, including operators, string formatting, namespaces, classes, errors,
JButton b = (JButton)ae.getSource();
and exceptions
b.setEnabled(false);
sayHello();
Object-oriented programming concepts
}
} );
File input/output
}
Python's intrinsic functions
private void sayHello(){
JFrame helloFrame;
Formatting, parsing, and manipulating strings
JLabel helloLabel;
Font font;
with the Java APIs andFrame");
working with Java Streams
helloFrame Interfacing
= new JFrame("Hello
helloLabel=Using
newPython
JLabel("Hello
World");
and Java Swing to create GUIs
font = new Font("Arial", Font.BOLD, 20);
helloLabel.setFont(font);
Working with SQL and JDBC(TM)
helloFrame.getContentPane().add(helloLabel);
helloFrame.pack();
Python and Java applets
helloFrame.setVisible(true);
In addition, the book contains instructions for downloading and installing the Python
}
language
and the
Java Development
(JDK). Terminology, definitions, explanations,
public static
void
main(String
[]Kitargs){
numerous
make this book a useful learning experience.
MyFrameandframe
= code
newsamples
MyFrame();
frame.setTitle("My Frame");
Whether you are a sophisticated computer user new to programming or a serious
}
application developer, Python Programming with the Java(TM) Class Libraries will
}
give you insight into the power of Python and the know-how to put it to work.
Here's the JavaScript (Rhino at JavaScript 1.4) version.

777

function MyFrame(){
sayHello = new Packages.javax.swing.JButton("say hello");

Python Programming with the Java Class Libraries: A Tutorial for Building
sayHello.setMnemonic('h');
and Enterprise Applications with Jython
this.frame Web
= new
Packages.javax.swing.JFrame();
By Richard Hightower

this.frame.getContentPane().add(sayHello);
Publisher: Addison Wesley
this.frame.setVisible(true);
Pub Date: June 28, 2002
this.frame.pack();
ISBN: 0-201-61616-5new Packages.java.awt.event.ActionListener() {
sayHello.addActionListener(
Table of

Pages:
640
__parent__ : this,
Contents
actionPerformed : function(ae) {
Characterized by ease of use, richness of expression, and concise syntax, Python has
ae.getSource().setEnabled(false);
remained a premier programming language for more than a decade, and is used by
this.__parent__.sayHello();
novices and professionals alike. In particular, its close relationship to Java(TM) makes
}
the two languages, when used in combination, ideal for Web and distributed enterprise
} );
application development.

function sayHello(){
This tutorial
begins
with coverage of some of the basics of Python programming.
Using
helloFrame
= new
Packages.javax.swing.JFrame("Hello
Frame");
plenty
of
skill-building
exercises
and
interactive
programming
sessions,
this
book
will
helloLabel= new Packages.javax.swing.JLabel("Hello World");
help
those
new
to
programming
develop
an
understanding
of
concepts
and
practical
font = new java.awt.Font("Arial", java.awt.Font.BOLD, 20);
techniques. For experienced programmers, the book demonstrates Python's breadth of
helloLabel.setFont(font);
capabilities and shows the ways that Python interfaces with Java APIs for professional
helloFrame.getContentPane().add(helloLabel);
application development.
helloFrame.pack();
helloFrame.setVisible(true);
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
}
and Enterprise Applications with Jython covers important topics such as:

this.sayHello=sayHello;
}

Fundamental programming concepts, including statements, expressions,


interpreters, and compilers

function main(){
Python basics, including operators, string formatting, namespaces, classes, errors,
frame = new MyFrame();
and exceptions Hello");
frame.frame.setTitle("My
}
Object-oriented programming concepts
main();
File input/output

The Jython Version

Python's intrinsic functions

from javax.swing import JFrame, JButton, JLabel


Formatting,
parsing, and manipulating strings
from java.awt import
Font
Interfacing with the Java APIs and working with Java Streams
class MyFrame (JFrame):
def __init__(self):
Using Python and Java Swing to create GUIs
sayHello = JButton("say hello", mnemonic='h')
self.contentPane.add(sayHello)
Working with SQL and JDBC(TM)
self.visible=1
self.pack()Python and Java applets
sayHello.actionPerformed = self.__sayHello
In addition, the book contains instructions for downloading and installing the Python
language and the Java
Development Kit (JDK). Terminology, definitions, explanations,
def __sayHello(self,
ae):
and numerous code samples make this book a useful learning experience.
ae.source.enabled=0
helloFrame = JFrame("Hello Frame")
Whether you
are a sophisticated World",
computer user
new to programming or a serious
helloLabel=
JLabel("Hello
font=Font("Arial",
Font.BOLD, 20))
application developer, Python Programming with the Java(TM) Class Libraries will
helloFrame.contentPane.add(helloLabel)
give you insight into the power of Python and the know-how to put it to work.
helloFrame.pack()
helloFrame.visible=1

777

if __name__=="__main__":
frame = MyFrame(title = "My Frame")

Python Programming with the Java Class Libraries: A Tutorial for Building
Notice how well Jython
integrates with the JavaBean properties and event model. Also notice how much it packs
Web and Enterprise Applications with Jython
into a small package (it's about two-thirds the size of the JavaScript version).
By Richard Hightower

What Does It All


Mean?
Publisher:
Addison Wesley
Pub Date: June 28, 2002
0-201-61616-5
Basically that Python is the ISBN:
best scripting
language for the JVM. Here's why:

Table of
Contents

Pages: 640

Ease of use. Python


was designed
to of
beuse,
easyrichness
for beginners.
In Virginia,
high school
students
arehas
taught
Characterized
by ease
of expression,
and concise
syntax,
Python
how to program
with
it.
remained a premier programming language for more than a decade, and is used by

novices and professionals alike. In particular, its close relationship to Java(TM) makes
Embeddability. On a scale from 1 to 10, Python scores 10 for embeddability.
the two languages, when used in combination, ideal for Web and distributed enterprise
application
Resemblance to
the parentdevelopment.
language. Jython is syntactically identical to Python.
Thishas
tutorial
coverageofofSmalltalk,
some of the
basics Icon,
of Python
programming. Using
Features. Python
somebegins
of the with
best features
Scheme,
and Java.
plenty of skill-building exercises and interactive programming sessions, this book will
thosehas
new
to programming
develop an understanding
concepts
andE)
practical
String parsing.help
Python
libraries
for regular-expression
string parsing of
(see
Appendix
and slice
techniques.
For
experienced
programmers,
the
book
demonstrates
Python's
breadth of
notation, as well as other features that make string parsing easy.
capabilities and shows the ways that Python interfaces with Java APIs for professional
Productivity. Python
has an
extensive class library as well as built-in language support for collection
application
development.
objects (including collection literals for defining collections). These make Python strikingly productive.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
Working well with
Java classes
and APIs. In
Jython
youcovers
instantiate
and subclass
Javaas:classes and
and Enterprise
Applications
with
Jython
important
topics such
interfaces, invoke Java methods, set up bean events, and work with JavaBean properties. You can also
compile Jython into Java classes to create JavaBeans, servlets, and applets.
Fundamental programming concepts, including statements, expressions,
interpreters,
and compilers
Development environment
and debugging.
Jython has a good interactive interpreter, but its development
environment is its weak point. Python has some mature IDEs, but Jython has nothing. If it did, it would
Python
basics,
including
operators,
formatting,
classes, errors,
give Java a serious run
for its
money
as the most
popularstring
language
for the namespaces,
JVM.
and exceptions

CONTENTS
Object-oriented programming
concepts
File input/output
Python's intrinsic functions
Formatting, parsing, and manipulating strings
Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs
Working with SQL and JDBC(TM)
Python and Java applets
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
CONTENTS
Web and Enterprise Applications with Jython
By Richard Hightower

Appendix D. Publisher:
Java Addison
and Python:
A Comparison
Wesley
Pub Date: June 28, 2002

Python 101
ISBN: 0-201-61616-5
Table of
A GUI Application
Pages: 640
Contents
A Statistics Application
Characterized
by ease of use, richness of expression, and concise syntax, Python has
A String Parsing
Example
remained a premier programming language for more than a decade, and is used by
Embedding Jython in Java

novices and professionals alike. In particular, its close relationship to Java(TM) makes
tworelative
languages,
when
usedand
in combination,
for Web tests
and distributed
This appendix looks the
at the
merits
of Java
Python using ideal
the following
as the basisenterprise
for
application
development.
comparison: (1) a GUI application, (2) a statistics application, (3) a simple example of string parsing, and (4) an
application with an embedded script.
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
Python 101 help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
and
the ways that Python interfaces with Java APIs for professional
Here's a Python classcapabilities
followed by
itsshows
Java equivalent.
application development.
Python:
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
class Employee:
and Enterprise Applications with Jython covers important topics such as:

def __init__(self, fname="John", lname="Doe", id=1, manager=None, dept=1):


self.__firstName
=
fname
Fundamental
programming
concepts,
self.__lastName
=
lnameincluding statements, expressions,
self.__idinterpreters, and compilers
=
id
self.__manager
=
manager
Python basics, including operators, string formatting, namespaces, classes, errors,
self.__dept
=
dept
and exceptions

def getManager(self):
Object-oriented programming concepts
return self.__manager
File input/output

def __str__(self):
intrinsic functions self.__firstName, self.__id
values = Python's
self.__lastName,
return join(values,',')
Formatting, parsing, and manipulating strings
Java:

Interfacing with the Java APIs and working with Java Streams

public class Employee{


Python and Java
Swing to create GUIs
private StringUsing
firstName,
lastName;
private int id, dept;
Working
with SQL and JDBC(TM)
private Employee
manager;
Python and Java applets

public Employee(){
firstName
= book
"John";
In addition, the
contains instructions for downloading and installing the Python
lastName
=
"Doe";
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
id and
= numerous
1;
code samples make this book a useful learning experience.
vmanager=null;
dept=1;
Whether you are a sophisticated computer user new to programming or a serious
}
application developer, Python Programming with the Java(TM) Class Libraries will
public Employee(String
fname,
intto id,
Employee
manager, int
give you insight into the
power of String
Python andlname,
the know-how
put it to
work.
firstName
=
fname;
lastName
=
lname;
this.id
=
id;
this.manager =
manager;

777

this.dept
= withdept;
Python Programming
the Java Class Libraries: A Tutorial for Building
}

Web and Enterprise Applications with Jython


By Richard Hightower

public Employee getManager(){


return
manager;
Publisher:
Addison Wesley
}
Pub Date: June 28, 2002
Table of
public
Contents

}
...
...

ISBN: 0-201-61616-5

String Pages:
toString(){
640
StringBuffer buf = new StringBuffer();
buf.append(lastName+',');
Characterized by ease of use, richness of expression, and concise syntax, Python has
buf.append(firstName+',');
remained a premier programming language for more than a decade, and is used by
buf.append(""+id);
novices and professionals alike. In particular, its close relationship to Java(TM) makes
return
the two buf.toString();
languages, when used in combination, ideal for Web and distributed enterprise
application development.

This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
Similar to Java's this
, Python'sFor
self
is a reference
to the class
referred to by
the firstbreadth
argument
techniques.
experienced
programmers,
theinstance
book demonstrates
Python's
of in
each method. There'scapabilities
no separateand
declaration
member
variables;
they're declared
a value. (You
shows theforways
that Python
interfaces
with Javawhen
APIsassigned
for professional
can declare class as well
as
instance
variables.)
Python's
__str__()
method
is
equivalent
to
Java's
application development.
toString().
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
In Python, to create an
of Employee
it tocovers
the screen
you enter
thesuch
following:
andinstance
Enterprise
Applicationsand
withprint
Jython
important
topics
as:

print Employee()
Fundamental programming concepts, including statements, expressions,
The equivalent in Java is interpreters, and compilers

System.out.println(new
Employee());
Python basics,
including operators, string formatting, namespaces, classes, errors,
and exceptions
Here's how to create two instances of Employee ,joe and ron, and print them to the console. Joe is Ron's
manager. We get him by invoking
the ronprogramming
instance's getManager()
method.
Object-oriented
concepts
Python:

joe =
ron =
print
print

File input/output

Employee("Joe",
"Battista",
Python's intrinsic
functions 100)
Employee(manager=joe, id=101, lname="Furgeson", fname="Ron")
ron
Formatting, parsing, and manipulating strings
ron.getManager()
Interfacing with the Java APIs and working with Java Streams

Java:

Using Python and Java Swing to create GUIs

Employee joe=new Employee("Joe","Batista",100,null,1);


with SQL and JDBC(TM)
Employee ron=new Working
Employee("Ron","Furgeson",101,joe,1);
System.out.println(ron);
Python and Java applets
System.out.println(ron.getManager());
In addition,
the book contains instructions for downloading and installing the Python
As you can see, the syntax
is similar.
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous
code samples
this book
usefulthe
learning
experience.
Jython uses named arguments
and default
values.make
This means
thata when
ron instance
is created the
arguments are called out of order, which should be familiar to those of you who've used Visual Basic or
you are awith
sophisticated
programming
or a serious
VBScript. For those Whether
of you unfamiliar
this idea, computer
think of ituser
this new
way:toYou
can call methods
as you normally
application
developer,
Python
Programming
with
the
Java(TM)
Class
Libraries
do in Java, or you can do it the Python way, passing the method name/value pairs and saving
yourselfwill
some
give
you insight
intoyou
the ever
power
of Python
and several
the know-how
to work.
coding, not to mention
headaches.
Have
been
stuck with
versionstoofput
theitsame
method when all
you wanted was different default values? Every default value is another overloaded method, which can get
messy.

777

A good example of the use of named arguments is Python's GridBag utility class, which manages the

infamousGridBagLayout
manager. I'vewith
created
similar
in Java that
uses overloaded
methods to
Python Programming
thesomething
Java Class
Libraries:
A Tutorial
for Building
createGridBag constraints.
Web and Enterprise Applications with Jython
By Richard Hightower

A Simple GUI Prototype


Publisher: Addison Wesley
PubNow
Date:
June
28, 2002
We have our simple class.
we'll
create
a simple GUI prototype. (Like the class, it's nonsensical since its
ISBN: 0-201-61616-5
only purpose
is
for
illustration.)
Table of

Contents

Pages: 640

Fire up the Python interactive interpreter, typing in Jython at the system prompt. Then import JFrame from
javax.swing.
Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
>>> from javax.swing
import JFrame
novices and professionals
alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
Create an instance ofapplication
the frame, development.
set its size to 200,200, and make it visible.

>>> frame=JFrame("My
Prototype",visible=1,size=(200,200))
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
This took only one line of code because in Jython any bean property of a class (by which I mean a property
help those new to programming develop an understanding of concepts and practical
defined by getter and setter methodsthat is, the Java Bean design pattern for properties) can be set during the
techniques. For experienced programmers, the book demonstrates Python's breadth of
constructor call using named arguments.
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
Now let's add some components:
labels, text fields, and a button. Import the necessary classes from javax.swing.
Python Programming
withJButton,JTextField,JLabel,JPanel
the Java(TM) Class Libraries: A Tutorial for Building Web
>>> from javax.swing
import
and Enterprise Applications with Jython covers important topics such as:
We could have entered from javax.swing import *, as we do in Java, but that would have
imported every class into our namespace, which Python considers bad style. Python's way is to let us view and
Fundamental programming concepts, including statements, expressions,
manipulate a namespace.
interpreters, and compilers

>>> dir()
Python basics,
including operators,
string formatting,
namespaces, classes,
errors,
['JButton', 'JFrame',
'JLabel',
'JTextField',
'__name__',
'frame']
and exceptions
Create a pane, using JFrame'scontentPane property.
Object-oriented programming concepts

>>> pane = JPanel()


File input/output
>>> frame.contentPane.add(pane)
javax.swing.JPanel[,0,0,0x0,invalid,layout=java.awt.FlowLayout,alignmentX=
Python's intrinsic functions
null,alignmentY=null,border=,flags=34,maximumSize=,minimumSize=,preferredSize
,default Layout=java.awt.FlowLayout[hgap=5,vgap=5,align=center]]
Formatting, parsing, and manipulating strings
If this were Java, we'd haveInterfacing
to call frame.getContentPane()
to create
pane because Java does not
with the Java APIs and working with
Java aStreams
treat bean properties like instance variables.
Using Python and Java Swing to create GUIs
To lay out the pane we're going to use the infamous GridBagLayout, which is the most complex of Jython's
layout managers. To tame itWorking
we'll usewith
the SQL
GridBag
utility class. Notice how few lines of code it takes up.
and JDBC(TM)
Import the GridBag helper
class.and
Then
an instance of it and associate it with the pane.
Python
Javacreate
applets

>>> from pawtIn addition,


importtheGridBag
book contains instructions for downloading and installing the Python
>>> bag = GridBag(pane)
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Add the first component, a label, to GridBag, which will use all of GridBagConstraints's default
values.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
>>> bag.add(JLabel("Name"))
give you insight into the power of Python and the know-how to put it to work.

>>> frame.validate()

777

Add another label on the second row of the grid.

>>> bag.add(JLabel("ID"), gridy=1)

>>> frame.validate()
Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython

Add a text field on the


first rowHightower
in the second column, and pack the frame.
By Richard

>>> name = JTextField(25)


Publisher: Addison Wesley
>>> bag.add(name, gridx=1, weightx=80.0)
Pub Date: June 28, 2002
>>> frame.pack()
Table of
Addanother
text field
Contents

ISBN: 0-201-61616-5

for

Pages:
640
the
employee

ID to the right on the second row, and pack the frame.

>>> id = JTextField(10)
Characterized by ease of use, richness of expression, and concise syntax, Python has
>>> bag.add(id,
gridx=1,
gridy=1, language
weightx=80.0)
remained
a premier programming
for more than a decade, and is used by
>>> frame.pack()
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
Not what we want, isapplication
it? The textdevelopment.
field components look silly because I accidentally (on purpose) aligned them
centered, not at the left, in their cells. Let's fix this.
This tutorial begins with coverage of some of the basics of Python programming. Using
Remove the ID and name.
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
>>> pane.remove(id)
techniques. For experienced programmers, the book demonstrates Python's breadth of
>>> pane.remove(name)
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
Put them back with the correct alignment.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web

>>> bag.add(name, gridx=1, weightx=80.00, anchor='WEST')


and Enterprise Applications with Jython covers important topics such as:
>>> bag.add(id, gridx=1, gridy=1, weightx=80.0, anchor='WEST')
>>> frame.pack()

Fundamental programming concepts, including statements, expressions,


Jython handles bean eventsinterpreters,
easily because
uses introspection and reflection to create event properties. With the
anditcompilers
JavaBeans Event design pattern, event properties equate to the method name in a method's event listener
interface.
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
To demonstrate assigning a function or method to an event property, we'll set up an Okay button that prints an
employee's name and ID when
clicked.
Object-oriented
programming concepts
Create and add a button to File
the GUI.
input/output

>>> okay = JButton("Okay")


Python's intrinsic functions
>>> bag.add(okay, gridx=1, gridy=2, anchor='CENTER')
>>> frame.pack() Formatting, parsing, and manipulating strings
withofthe
APIs
with Java Streams
Create a function that printsInterfacing
out the value
theJava
name
andand
ID working
text.

>>> def handleOkay(event):


Using Python and Java Swing to create GUIs
...
print "Name " + name.text
with SQL and JDBC(TM)
...
print "IDWorking
" + id.text
...
Python and Java applets
>>> okay.actionPerformed=handleOkay
Inname
addition,
instructions for downloading and installing the Python
Enter some text in the
and the
ID book
fields,contains
and hit Okay.
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.

A GUI Application

Whether you are a sophisticated computer user new to programming or a serious


application
Python
Programming
Java(TM)
Class
Libraries
will
Now let's create a GUI
based ondeveloper,
our prototype
in both
Jython andwith
Java.the
The
following
example
shows
our
give
you
insight
into
the
power
of
Python
and
the
know-how
to
put
it
to
work.
Python employee form; after that is its Java equivalent.
Python:

777

from javax.swing import JFrame, JButton, JTextField, JLabel, JPanel

from string import


split
Python Programming
with the Java Class Libraries: A Tutorial for Building
from pawt import
GridBag
Web and
Enterprise Applications with Jython
from EmployeeByRichard
import
Employee
Hightower
class EmployeeForm(JFrame):
Publisher: Addison Wesley
def __init__(self):
Pub Date: June 28, 2002
JFrame.__init__(self,
ISBN: 0-201-61616-5"Employee Form")
Table ofpane = JPanel()

Pages: 640
Contents
self.contentPane.add(pane)
bag =Characterized
GridBag(pane)
by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
#Create
a name alike.
andInid
text itsfield.
novices
and professionals
particular,
close relationship to Java(TM) makes
self.__name
= JTextField(25)
the two languages,
when used in combination, ideal for Web and distributed enterprise
self.__id
= development.
JTextField(10)
application

#Create
andwith
add
a "Name"
and
"ID"of label.
This
tutorial begins
coverage
of some of
the basics
Python programming. Using
name plenty
= JLabel("Name",
labelFor=self.__name,
displayedMnemonic=ord('N'
of skill-building exercises
and interactive programming sessions,
this book will
bag.add(name)
help those new to programming develop an understanding of concepts and practical
id = techniques.
JLabel("ID",
labelFor=self.__id,
displayedMnemonic=ord('I'))
For experienced
programmers, the book demonstrates
Python's breadth of
bag.add(id,
gridy=1)
capabilities and
shows the ways that Python interfaces with Java APIs for professional
application development.

# Add the name and ID text field to the form.


Python Programming with the
Java(TM) Class
Libraries: A Tutorial
for Building Web
bag.add(self.__name,
gridx=1,
weightx=80.00,
anchor='WEST')
and Enterprise Applications
with Jythongridy=1,
covers important
topics such as:
bag.add(self.__id,
gridx=1,
anchor='WEST')
#Create an okay button, add it, and set up its event handler.
Fundamental programming
concepts, including statements, expressions,
okay = JButton("Okay",
mnemonic=ord('O'))
interpreters,
and compilers
bag.add(okay,
gridx=1,
gridy=2, anchor='EAST')
okay.actionPerformed=self.handleOkay
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions

self.visible=1
self.pack()
Object-oriented programming concepts
def handleOkay(self,
event):
File input/output
fname, lname = split(self.__name.text, " ")
Python's intrinsic functions
id = int(self.__id.text)
employee = Employee(fname, lname, id)
Formatting, parsing, and manipulating strings
print employee
Interfacing with the Java APIs and working with Java Streams

if __name__=="__main__":EmployeeForm()
Java:

import
import
import
import
import
import

Using Python and Java Swing to create GUIs


Working with SQL and JDBC(TM)

javax.swing.*;
java.awt.GridBagLayout;
Python and Java applets
java.awt.GridBagConstraints;
java.awt.event.ActionListener;
In addition, the book contains instructions for downloading and installing the Python
java.awt.event.ActionEvent;
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
employee.Employee;
and numerous code samples make this book a useful learning experience.

public class Whether


EmployeeForm
extendscomputer
JFrame{
you are a sophisticated
user new to programming or a serious
private JTextField
name;Python Programming with the Java(TM) Class Libraries will
application developer,
private JTextField
give you insightid;
into the power of Python and the know-how to put it to work.
public EmployeeForm(){
super("Employee Form");
JPanel pane = new JPanel();

777

getContentPane().add(pane);
Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython

pane.setLayout(new
GridBagLayout());
By Richard Hightower
// Create
a Addison
name Wesley
and id text field.
Publisher:
name = new JTextField(25);
Pub Date: June 28, 2002
id = new JTextField(10);
ISBN: 0-201-61616-5

Table of
Contents//

Pages: 640

Create and add a "Name" and "ID" label.


JLabel nameLabel
= bynew
JLabel("Name");
Characterized
ease of
use, richness of expression, and concise syntax, Python has
nameLabel.setLabelFor(name);
remained a premier programming language for more than a decade, and is used by
nameLabel.setDisplayedMnemonic('N');
novices and professionals alike. In particular, its close relationship to Java(TM) makes
GridBagConstraints
constraint
= new GridBagConstraints();
the two languages,
when used in combination,
ideal for Web and distributed enterprise
pane.add(nameLabel,
constraint);
application development.
JLabel idLabel
= new
This tutorial
beginsJLabel("ID");
with coverage of some of the basics of Python programming. Using
idLabel.setLabelFor(id);
plenty of skill-building exercises and interactive programming sessions, this book will
idLabel.setDisplayedMnemonic('I');
help those new to programming develop an understanding of concepts and practical
constraint.gridy=1;
techniques. For experienced programmers, the book demonstrates Python's breadth of
pane.add(idLabel,
constraint);
capabilities and
shows the ways that Python interfaces with Java APIs for professional
application development.

// Add the name and ID text field to the form.


Python Programming
with the Java(TM) Class Libraries: A Tutorial for Building Web
constraint.gridy=0;
constraint.gridx=1;
and Enterprise Applications with Jython covers important topics such as:
constraint.weightx=80.00;
constraint.anchor=GridBagConstraints.WEST;
pane.add(name, constraint);
Fundamental programming concepts, including statements, expressions,
constraint.gridy=1;
interpreters, and compilers
pane.add(id, constraint);
Python basics, including operators, string formatting, namespaces, classes, errors,

// Create
an okay button, add it, and set up its event handler.
and exceptions
JButton okay = new JButton("Okay");
okay.setMnemonic('O');
Object-oriented programming concepts
constraint.gridx=1; constraint.gridy=2;
constraint.anchor=GridBagConstraints.EAST;
File input/output
pane.add(okay, constraint);
Python's intrinsic functions
okay.addActionListener(new
ActionListener(){
public void actionPerformed(ActionEvent event){
Formatting, parsing, and manipulating strings
handleOkay();
}
Interfacing with the Java APIs and working with Java Streams
} );
Using Python and Java Swing to create GUIs

this.setVisible(true);
this.pack(); Working with SQL and JDBC(TM)
}
Python and Java applets

public void handleOkay(){


In addition, the book contains instructions for downloading and installing the Python
language
and the Java
Development Kit (JDK). Terminology, definitions, explanations,
String name,
fname,
lname;
and
numerous
code
samples
make this book a useful learning experience.
int index=0;
int id =0;
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
name = this.name.getText();
give you insight into the
power of Python and the know-how to put it to work.
index = name.indexOf("
");

fname = name.substring(0, index);


lname = name.substring(index+1, name.length());

777

id = Integer.parseInt(this.id.getText());

Python Programming with the Java Class Libraries: A Tutorial for Building

Employee employee
= newApplications
Employee(fname,
Web and Enterprise
with Jython lname, id, null, 100);
System.out.println(""+employee);
By Richard Hightower
}

public static
voidAddison
main(String
[] args){
Publisher:
Wesley
new EmployeeForm();
Pub Date: June 28, 2002
}
ISBN: 0-201-61616-5

Table of
Contents

Pages: 640

The Jython version is 1,290 characters; the Java version is 2,139 characters.
Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
A Statistics novices
Application
and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
development.
Remember the houseapplication
price sample
application we created in Chapter 4? You might want to go back and refresh
your memory because we're going to be using it to continue our Python/Java comparison. I'm not going to repeat
begins withthe
coverage
of some
the basics of
programming.
Using the
the information you'llThis
findtutorial
there, particularly
breakdown
andofexplanation
of Python
the code,
but I will highlight
plenty
of
skill-building
exercises
and
interactive
programming
sessions,
this
book
important functions, as I did in Chapter 4, and show you the full code examples. A suggestion: Place a will
bookmark
those
to programming
develop
an understanding
of concepts and practical
at the section on the help
house
pricenew
example
in that chapter
for easy
referral.
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
getRange() application development.
ThegetRange()Python
functionProgramming
iterates through
list Java(TM)
of numbersClass
passed
to it to calculate
thefor
minimum
witha the
Libraries:
A Tutorial
Buildingand
Web
maximum values in and
a list.Enterprise
It returns Applications
these values, with
with Jython
their range,
inimportant
a tuple. Here's
way
covers
topicsone
such
as:to implement it:

def getRange (nums):


Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
min = 300000000

max = -300000000
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
for item in nums:

if (item > max): max = item


Object-oriented
concepts
if (item
< min): programming
min = item
return (min, max,
max-min)
File input/output
Here's another, better, way:Python's intrinsic functions

def getRange (nums):


Formatting, parsing, and manipulating strings
return (min(nums), max(nums), max(nums)-min(nums))
Interfacing with the Java APIs and working with Java Streams
With the first implementation, you have to be sure that the values passed to getRange() are within the
minimum-maximum range.Using
With Python
the second
you don't
and implementation,
Java Swing to create
GUIshave to do that, thanks to the built-in
min() and max() functions, which work with all numeric types.
Working with SQL and JDBC(TM)

getMean()

Python and Java applets

ThegetMean() function
calculates
thecontains
mean of instructions
a sequence of
by iterating
throughthe
the Python
sequence,
In addition,
the book
fornumbers
downloading
and installing
summing the values,language
and then and
dividing
the
sum
by
the
sequence
length.
It
also
determines
if
the
result
is a sample
the Java Development Kit (JDK). Terminology, definitions, explanations,
mean or a populationand
mean.
numerous code samples make this book a useful learning experience.

def getMean (nums,


sample):
Whether you
are a sophisticated computer user new to programming or a serious
sum = 0.0 application developer,
# holds
value with
of the
sum
Pythonthe
Programming
Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

# iterate through the sequence


# of numbers and sum them
for x in nums:
sum = sum + x

777

# Check
to see if with
this
a Class
sample
meanA Tutorial for Building
Python Programming
the is
Java
Libraries:
Web and Enterprise Applications with Jython
if(sample):
By Richard=Hightower
average
sum / (len(nums)-1)
Publisher:
Addison
Wesley
# Else
it is
a population
mean

else:

Pub Date: June 28, 2002

averageISBN:
= sum
/ len(nums)
0-201-61616-5
Table of
return average
Pages: 640
Contents

As with getRange()
, Python has
better
wayrichness
to find the
mean. It mayand
surprise
you.
Characterized
by aease
of use,
of expression,
concise
syntax, Python has

remained a premier programming language for more than a decade, and is used by

def getMean (nums,


sample):
novices and professionals alike. In particular, its close relationship to Java(TM) makes
sum = reduce(lambda
a, b: a+b, nums)
the two languages, when used in combination, ideal for Web and distributed enterprise
if sample:application
average
=
sum / (len(nums)-1)
development.
else: average = sum / len(nums)
This tutorial begins with coverage of some of the basics of Python programming. Using

return average
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
What's new here is the reduce() built-in function, which takes two arguments, function and
techniques. For experienced programmers, the book demonstrates Python's breadth of
sequence .function
is specified with the lambda keyword, which makes it anonymous. reduce()
capabilities and shows the ways that Python interfaces with Java APIs for professional
appliesfunction to two items in the sequence, cumulatively from left to right, reducing it to a single value,
application development.
in our case sum.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
The result is the same as with our first implementation of getMean(), but it's a lot shorter.
and Enterprise Applications with Jython covers important topics such as:

getMode()

Fundamental programming concepts, including statements, expressions,


and compilers
ThegetMode() functioninterpreters,
finds the value
that repeats most often in a sequence. First it duplicates the sequence
(before modifying it); then it iterates through it, counting the occurrences of current items via the built-in
Python basics, including operators, string formatting, namespaces, classes, errors,
count() method. Once an item is counted, it's removed from the duplicated sequence.
and exceptions

def getMode (nums):


Object-oriented programming concepts
#
# make File
a input/output
duplicate copy of the nums argument
duplicate = nums[:]
highest_count Python's
= -100
intrinsic functions
mode = None
Formatting, parsing, and manipulating strings
#
# calculate the highest_count and the mode
Interfacing with the Java APIs and working with Java Streams
for item in nums:
Python and Java Swing to create GUIs
count =Using
duplicate.count(item)
if (count
== 0): continue
Working with SQL and JDBC(TM)
if (count > highest_count):
highest_count
= count
Python and Java applets
mode = item
In addition, the book contains instructions for downloading and installing the Python

while(duplicate.count(item)
> 0):
language and the Java Development Kit (JDK).
Terminology, definitions, explanations,
duplicate.remove(item)
and numerous
code samples make this book a useful learning experience.
return mode

getMedian()

Whether you are a sophisticated computer user new to programming or a serious


application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

ThegetMedian() function finds the middlemost value once the sequence is sorted.

777

def getMedian (nums):


"Find the Median number"

Python Programming with the Java Class Libraries: A Tutorial for Building

# Create
duplicate
sincewith
we Jython
are
Web andaEnterprise
Applications
# going to modify
it.
By Richard Hightower
seq = nums[:]
Publisher: Addison Wesley

# SortPubthe
list of numbers.
Date: June 28, 2002
seq.sort()
ISBN: 0-201-61616-5

Table of

Pages: 640

Contents = None # to hold the median value


median

Characterized by ease of use, richness of expression, and concise syntax, Python has

length = len(seq)
# to hold the length of the seq
remained a premier programming language for more than a decade, and is used by

novices and professionals alike. In particular, its close relationship to Java(TM) makes

# Check
to see if the length is
the two languages, when used in combination, ideal for Web and distributed enterprise
# an even number.
application development.
if ( ( length % 2) == 0):
# Since
it coverage
is an ofeven
number,
This tutorial
begins with
some of
the basics of Python programming. Using
#
add
the
two
middle
number
together.
plenty of skill-building exercises and interactive programming
sessions, this book will
index
length
/ 2
help=those
new to programming
develop an understanding of concepts and practical
median
= (seq[index-1]
+ seq[index])
/2.0
techniques.
For experienced programmers,
the book demonstrates
Python's breadth of
else:
capabilities and shows the ways that Python interfaces with Java APIs for professional
# Since
it is an odd number,
application
development.
# just grab the middle number.
index
= Programming
(length /with
2)the Java(TM) Class Libraries: A Tutorial for Building Web
Python
median
= seq[index]
and Enterprise
Applications with Jython covers important topics such as:
return median
Fundamental programming concepts, including statements, expressions,

reportStatistics() interpreters, and compilers

ThereportStatistics()
calls all of
the functions
describednamespaces,
and stores their
return
values
Python function
basics, including
operators,
stringjust
formatting,
classes,
errors,
in two dictionaries, averages
and ranges. It then places these dictionaries in another dictionary called
and exceptions
report, which it returns.
Object-oriented programming concepts

def reportStatistics (nums):


File input/output
# get central
tendencies
averages = {
Python's intrinsic functions
"mean":getMean(nums,0),
"median":getMedian(nums),
Formatting, parsing, and manipulating strings
"mode":getMode(nums)
}
Interfacing with the Java APIs and working with Java Streams
# get range
Using Python and Java Swing to create GUIs
range = getRange(nums)
# put ranges
dictionary
Working in
with a
SQL
and JDBC(TM)
ranges = {
Python and Java applets
"min":range[0],
"max":range[1],
In addition, the book contains instructions for downloading and installing the Python
"range":range[2]
} language and the Java Development Kit (JDK). Terminology, definitions, explanations,
report = {and numerous code samples make this book a useful learning experience.
"averages": averages,
Whether you are a sophisticated computer user new to programming or a serious
"ranges": ranges
application developer, Python Programming with the Java(TM) Class Libraries will
}
give you insight into the power of Python and the know-how to put it to work.
return report

777

Notice that Python, unlike Java, has a built-in syntax that allows you to specify a dictionary (which is similar to a
Java hashtable) with a literal.

runReport()

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
Byfunction
Richard Hightower
TherunReport()
uses reportStatistics() to get and print the report dictionary.

from stat import


reportStatistics
Publisher:
Addison Wesley
house_in_awahtukee
=
[100000,
Pub Date: June
28, 2002 120000, 150000, 200000, 65000, 100000]
report = reportStatistics(house_in_awahtukee)
ISBN: 0-201-61616-5

Table of
Contents

Pages: 640

range_format = """
Range:
Characterized by ease of use, richness of expression, and concise syntax, Python has
The least expensive
houseprogramming
is %(min)20.2f
remained a premier
language for more than a decade, and is used by
The most expensive
is %(max)20.2f
novices andhouse
professionals
alike. In particular, its close relationship to Java(TM) makes
The range of the
house
price when
is used
%(range)20.2f
two languages,
in combination, ideal for Web and distributed enterprise
"""
application development.
average_format = """
Averages:
This tutorial begins with coverage of some of the basics of Python programming. Using
The mean house
price
is %(mean)20.2f
plenty
of skill-building
exercises and interactive programming sessions, this book will
The mode for help
house
price
is %(mode)20.2f
those new
to programming
develop an understanding of concepts and practical
The median house
price
is %(median)20.2f
techniques.
For experienced
programmers, the book demonstrates Python's breadth of
"""
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.

print range_format % report["ranges"]


Python Programming
with the Java(TM) Class Libraries: A Tutorial for Building Web
print average_format
% report["averages"]
and Enterprise Applications with Jython covers important topics such as:
The thing to notice here is the string format operator (%), which is like C's printf() function except that it
can work with dictionaries. It's one of my favorite Python features because it makes text reporting so easy. I've
Fundamental
programming concepts, including statements, expressions,
even used it to generate Java
code.
interpreters, and compilers
Here's Python's runReport() output:
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
Range:

The least expensive house is


65000.00
Object-oriented
programming concepts
The most expensive
house is
200000.00
The range of house price is
135000.00
File input/output

Averages:
Python's intrinsic functions
The mean house price is
122500.00
The mode for house
price
is
100000.00
Formatting, parsing, and manipulating
strings
The median house price is
110000.00
Interfacing with the Java APIs and working with Java Streams
Here's the Java version.

Using Python and Java Swing to create GUIs

package stat;
Working with SQL and JDBC(TM)
import java.util.ArrayList;
import java.util.Iterator;
Python and Java applets
import java.util.Collections;
import java.util.HashMap;

In addition, the book contains instructions for downloading and installing the Python
public class language
Stats and
{ the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.

public static
double getMean (ArrayList nums,
Whether you are a sophisticated computer user new to programming or a serious
boolean sample){
application developer, Python Programming with the Java(TM) Class Libraries will
// Define
mean that finds two types of mean,
give you insight into the power of Python and the know-how to put it to work.
// namely:
// population mean and sample mean
double sum=0.0;
double average=0.0;

777

Iterator
iterator =
nums.iterator();
Python Programming
with
the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython

while(iterator.hasNext())
By Richard Hightower
sum = sum +
((Double)iterator.next()).doubleValue();
Publisher:
Addison Wesley
//
Check
to2002
see if this is a sample mean.
Pub Date: June 28,
if(sample)
ISBN: 0-201-61616-5
Table of
average
= sum / nums.size()-1;
Pages: 640
Contentselse
average
= of
sum
nums.size();
Characterized
by ease
use,/richness
of expression, and concise syntax, Python has
return
average;
remained a premier programming language for more than a decade, and is used by

novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
public static
ArrayList
getRange (ArrayList nums){
application
development.

// Find the range. Returns a tuple with the

// minimum,
maximum,
and
range
value
This tutorial
begins with coverage
of some
of the
basics of
Python programming. Using
double
max; exercises and interactive programming sessions, this book will
plentymin,
of skill-building
ArrayList
ranges;
help those new
to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
min capabilities
=
and shows the ways that Python interfaces with Java APIs for professional
((Double)Collections.min(nums)).doubleValue();
application development.
max =
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
((Double)Collections.max(nums)).doubleValue();
and Enterprise Applications with Jython covers important topics such as:

ranges = new ArrayList();


ranges.add(new Double (min));
FundamentalDouble
programming
concepts, including statements, expressions,
ranges.add(new
(max));
interpreters, and
compilers
ranges.add(new
Double
(max-min));
Python basics, including operators, string formatting, namespaces, classes, errors,

return ranges;
and exceptions

Object-oriented programming concepts

public static double getMedian (ArrayList nums){


//
Find the Median number.
File input/output
// Create a duplicate since we are going to
Python's
intrinsicthe
functions
//
modify
sequence.
ArrayList seq = new ArrayList(nums);
Formatting, parsing, and manipulating strings

// Sort the list of numbers.


Interfacing with the Java APIs and working with Java Streams
Collections.sort(seq);
Using Python and Java Swing to create GUIs

double median = 0.0; // to hold the median value


Working with SQL and JDBC(TM)

int length = seq.size(); // to hold the length of


// the sequence
Python and Java applets
int index=0;
In addition, the book contains instructions for downloading and installing the Python
language
the Javato
Development
(JDK).
Terminology, definitions, explanations,
// and
Check
see if Kit
the
length
and numerous
code
samples
make
this
book
a
useful
learning experience.
// is an even number.

if ( ( length % 2) == 0){
Whether you are
new number,
to programming or a serious
//a sophisticated
Since it computer
is an user
even
application developer,
Python
Programming
with
the
Java(TM)together.
Class Libraries will
// add the two middle numbers
give you
insight
into
the
power
of
Python
and
the
know-how
to
put
it to work.
index = length / 2;
double m1 =
((Double)seq.get(index-1)).doubleValue();
double m2 =
((Double)seq.get(index)).doubleValue();

777

median
= (m1
+ the
m2)Java
/2.0;
Python
Programming
with
Class Libraries: A Tutorial for Building
} Web and Enterprise Applications with Jython
else{
By Richard Hightower
// Since
Publisher: Addison
Wesleyit

is an odd number,
//
just
grab
the middle number.
Pub Date: June 28, 2002
index
=
(length
/
2);
ISBN: 0-201-61616-5
median
=
Pages: 640
((Double)seq.get(index)).doubleValue();

Table of
Contents

} Characterized by ease of use, richness of expression, and concise syntax, Python has
return
median;
remained
a premier programming language for more than a decade, and is used by

novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
private static
intdevelopment.
countMode(Object object,
application

ArrayList list){
int This
index
0; with coverage of some of the basics of Python programming. Using
tutorial= begins
int plenty
count
= 0;
of skill-building
exercises and interactive programming sessions, this book will
do {help those new to programming develop an understanding of concepts and practical
index=Collections.binarySearch(list,object);
techniques.
For experienced programmers, the book demonstrates Python's breadth of
if(index
>=0)list.remove(index);
capabilities
and shows
the ways that Python interfaces with Java APIs for professional
count++;
application development.
}
Python
Programming
with the Java(TM) Class Libraries: A Tutorial for Building Web
while
(index
>=0);
and Enterprise
return
count;Applications with Jython covers important topics such as:

}
Fundamental
programming
concepts, including
public static double
getMode
(ArrayList
nums){statements, expressions,
and compilers
// Find interpreters,
the number
that repeats the most.
//
Make
a
duplicate
copy of the
Python basics, including operators, string formatting, namespaces, classes, errors,
//
nums
argument.
and exceptions
ArrayList duplicate = new ArrayList(nums);
Object-oriented programming concepts

Collections.sort(duplicate);
double highest_count
= -100;
File input/output
double mode = -100;
Python's intrinsic functions

Iterator iterator = nums.iterator();


Formatting,
parsing,
and manipulating
//
Iterate
through
nums strings
removing
// each item out of the duplicate.
Interfacing with the Java APIs and working with Java Streams
// Calculate the highest_count and the mode.
while(iterator.hasNext()){
Using Python and Java Swing to create GUIs
double count = 0;
Object
item
Working with
SQL=anditerator.next();
JDBC(TM)
// Count the number of times the item
//
occurs
the list.
Python
and Javain
applets
// If Count is 0, go to the next
In addition, the book
contains instructions for downloading and installing the Python
// iteration.
language
and the= Java
Development Kit (JDK).
Terminology, definitions, explanations,
count
countMode(item,
duplicate);
and numerous
code
samples
make
this
book
a
useful
learning experience.
if (count == 0) continue;
Whether you are//
a sophisticated
computer
new to programming
or a serious
Determine
the user
highest
count. The
application developer,
Python
Programming
with
the
Java(TM)
Class
Libraries will
// highest counted item is the mode.
give you
insight
into
the
power
of
Python
and
the
know-how
to
put
it
to
work.
if (count > highest_count){

777
}

highest_count = count;
mode = ((Double)item).doubleValue();

return
mode;
Python
Programming with the Java Class Libraries: A Tutorial for Building
}

Web and Enterprise Applications with Jython


By Richard Hightower

public static HashMap reportStatistics(


ArrayList nums){
Publisher: Addison Wesley
//
Get
central
tendencies.
Pub Date: June 28, 2002
HashMap ISBN:
averages
= new HashMap();
0-201-61616-5

Table of
Pages: 640
Contentsaverages.put("mean",

new Double(getMean(nums,false)));
Characterized
by ease of use, richness of expression, and concise syntax, Python has
averages.put("median",
remained a premier programming language for more than a decade, and is used by
new
Double(getMedian(nums)));
novices
and professionals
alike. In particular, its close relationship to Java(TM) makes
averages.put("mode",
Double(getMode(nums)));
the two languages, when usednew
in combination,
ideal for Web and distributed enterprise
application development.

// Get range.
ArrayList
= getRange(nums);
This tutorialrange
begins with
coverage of some of the basics of Python programming. Using
HashMap
= new
HashMap();
plenty ofranges
skill-building
exercises
and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
// Put
ranges programmers,
in a dictionary.
techniques.
For experienced
the book demonstrates Python's breadth of
ranges.put("min",
range.get(0));
capabilities and shows the
ways that Python interfaces with Java APIs for professional
ranges.put("max",
application development.range.get(1));

ranges.put("range",range.get(2));
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise
Applications
Jython covers important topics such as:
HashMap
report
= new with
HashMap();
report = new HashMap();
report.put("averages", averages);
Fundamental programming
concepts, including statements, expressions,
report.put("ranges",
ranges);
interpreters, and compilers

}
}

return report;
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
Object-oriented programming concepts

--- RunReport.java --package stat;


File input/output
Python's intrinsic functions
import java.util.ArrayList;
import java.text.MessageFormat;
Formatting, parsing, and manipulating strings
import java.util.HashMap;
Interfacing with the Java APIs and working with Java Streams

public class RunReport{


public static String
range_format
"" GUIs
+
Using Python
and Java Swing to=create
"Range: \n"+
"The least expensive
house
isJDBC(TM)
{0,number,currency} \n"+
Working with
SQL and
"The most expensive house is {1,number,currency} \n"+
"The range of house
price
is {2,number,currency} \n";
Python and
Java applets
public static String average_format = "" +
addition,
"Averages: In\n"
+ the book contains instructions for downloading and installing the Python
language price
and the Java
Kit (JDK). Terminology, definitions,
"The mean house
is Development
{0,number,currency}
\n"+ explanations,
and
numerous
code
samples
make
this
book
a
useful
learning
experience.
"The mode for house price is {1,number,currency} \n"+
"The median house price is
{2,number,currency} \n";
Whether you are a sophisticated computer user new to programming or a serious
developer, Python Programming
public staticapplication
void main(String
[] args){with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

ArrayList houses_in_awahtukee = new ArrayList();


houses_in_awahtukee.add(new Double(110000));
houses_in_awahtukee.add(new Double(190000));
houses_in_awahtukee.add(new Double(140000));

777

houses_in_awahtukee.add(new
Double(120000));
Python Programming with the Java
Class Libraries: A Tutorial for Building
houses_in_awahtukee.add(new
Double(190000));
Web and Enterprise Applications with
Jython
houses_in_awahtukee.add(new
Double(180000));
By Richard Hightower
houses_in_awahtukee.add(new Double(170000));
houses_in_awahtukee.add(new
Double(180000));
Publisher: Addison Wesley
houses_in_awahtukee.add(new
Double(180000));
Pub Date: June 28, 2002
houses_in_awahtukee.add(new
Double(190000));
ISBN: 0-201-61616-5
Table houses_in_awahtukee.add(new
of
Double(190000));
Pages: 640
Contents
houses_in_awahtukee.add(new Double(250000));
Characterized by ease of use, richness of expression, and concise syntax, Python has

HashMap
report
= programming language for more than a decade, and is used by
remained
a premier
Stats.reportStatistics(houses_in_awahtukee);
novices and professionals alike. In particular, its close relationship to Java(TM) makes
HashMap
ranges
= (HashMap)report.get("ranges");
the two
languages,
when used in combination, ideal for Web and distributed enterprise
HashMap
averages
=
application
development.
(HashMap)report.get("averages");
This tutorial begins with coverage of some of the basics of Python programming. Using

Objectplenty
[] ofm_args
= new
Object[]{
skill-building
exercises
and interactive programming sessions, this book will
averages.get("mean"),
help
those new to programming develop an understanding of concepts and practical
averages.get("mode"),
techniques.
For experienced programmers, the book demonstrates Python's breadth of
averages.get("median")}
; interfaces with Java APIs for professional
capabilities
and shows the ways that Python
application development.

Object [] r_args = new Object []{


Python
Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
ranges.get("min"),
andranges.get("max"),
Enterprise Applications with Jython covers important topics such as:
ranges.get("range")} ;
Fundamental programming concepts, including statements, expressions,
System.out.println(
interpreters, and compilers
MessageFormat.format(range_format,r_args));
Python basics, including operators, string formatting, namespaces, classes, errors,

System.out.println(
and exceptions
MessageFormat.format(average_format,m_args));
}

Object-oriented programming concepts

}
File input/output
Which one is shorter?

Python's intrinsic functions

A String Parsing
Example
Formatting,
parsing, and manipulating strings
Interfacing
with the
Javagoing
APIstoand
working
with Java
Streams of a commaTo compare Java and Python
string parsing,
we're
create
a readable
file consisting
delimited list of house prices.
Using Python and Java Swing to create GUIs

100000,100000,120000,150000,170000,170000,80000,50000
Working with SQL and JDBC(TM)
Here's the Python code broken down:
Python and Java applets
Open the file.
In addition, the book contains instructions for downloading and installing the Python
>>> file = open("data.txt")
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Read in the file data.
Whether you are a sophisticated computer user new to programming or a serious
>>> data = file.read()
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.
Import the split() function to parse the data.

777

>>> from string import split


>>> housePrices = split(data, ",")

For demonstration, show


thatProgramming
split() haswith
splitthe
the Java
data string
intoLibraries:
a list of strings.
Python
Class
A Tutorial for Building
Web and Enterprise Applications with Jython

>>> housePrices
By Richard Hightower
['100000', '100000', '120000', '150000', '170000', '170000', '80000', '50000'
Publisher: Addison Wesley

ConverthousePrices from strings to floating-point values.


Pub Date: June 28, 2002

0-201-61616-5
>>> Table
housePrices
=ISBN:
map(float,
housePrices)
of

Pages: 640

Contents

Show that housePrices is now a list of floating-point values.


Characterized by ease of use, richness of expression, and concise syntax, Python has
>>> housePrices
remained a premier programming language for more than a decade, and is used by
[100000.0, 100000.0,
120000.0,
170000.0,
80000.0, 50000.0
novices and professionals
alike.150000.0,
In particular, its170000.0,
close relationship
to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
Here's the actual code
(from runReport2.py).
application
development.

from
from
file
data

stat import
reportStatistics
This tutorial
begins with coverage of some of the basics of Python programming. Using
string import
split
plenty of skill-building
exercises and interactive programming sessions, this book will
= open("data.txt")
help those new to programming develop an understanding of concepts and practical
= file.read()
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional

housePrices =application
split(data,
",")
development.
housePrices = map(float, housePrices)
report = reportStatistics(housePrices)
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

range_format = """
Range:
Fundamental
concepts, including statements, expressions,
The least expensive
houseprogramming
is %(min)20.2f
interpreters,
The most expensive
houseand
iscompilers
%(max)20.2f
The range of house price is %(range)20.2f
Python basics, including operators, string formatting, namespaces, classes, errors,
"""
and exceptions

average_format = """
Object-oriented programming concepts
Averages:
The mean house price
is
%(mean)20.2f
File input/output
The mode for house price is
%(mode)20.2f
The median house Python's
priceintrinsic
is functions %(median)20.2f
"""print range_format
% report["ranges"]
Formatting, parsing,
and manipulating strings
print average_format
% report["averages"]
Interfacing
withmodule.
the Java Notice
APIs and
with
Java Streams
Here's the Java version of the
RunReport2
theworking
difference
in length.

package stat;

Using Python and Java Swing to create GUIs

Working with SQL and JDBC(TM)


import java.util.ArrayList;
import java.util.HashMap;
Python and Java applets
import java.util.StringTokenizer;
In addition, the book contains instructions for downloading and installing the Python

import java.text.MessageFormat;
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.

import java.io.FileReader;
import java.io.BufferedReader;
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will

public class give


RunReport2{
you insight into the power of Python and the know-how to put it to work.
public static String range_format = "" +
"Range: \n"+
"The least expensive house is {0,number,currency} \n" +
"The most expensive house is {1,number,currency} \n"+

777

"The range Python


of house
price with
is the
{2,number,currency}
\n";for Building
Programming
Java Class Libraries: A Tutorial
Web and Enterprise Applications with Jython

public staticByRichard
String
average_format = "" +
Hightower
"Averages: \n" +
"The mean house
price
isWesley
{0,number,currency} \n"+
Publisher:
Addison
"The mode forPubhouse
price
is {1,number,currency} \n"+
Date: June 28, 2002
"The median house
price
is
{2,number,currency} \n";
ISBN: 0-201-61616-5

Table of

Pages: 640

Contentsstatic void main(String [] args){


public

Characterized by ease of use, richness of expression, and concise syntax, Python has

ArrayList
= new
ArrayList();
remained ahouses_in_awahtukee
premier programming language for
more than
a decade, and is used by

novices and professionals alike. In particular, its close relationship to Java(TM) makes

try the
{ two languages, when used in combination, ideal for Web and distributed enterprise
BufferedReader
reader=new BufferedReader(
application
development.
new FileReader("data.txt"));
data
reader.readLine();
ThisString
tutorial begins
with=coverage
of some of the basics of Python programming. Using
StringTokenizer
tokens=
plenty
of skill-building exercises
and interactive programming sessions, this book will
new
StringTokenizer(data,
help those new to
programming
develop an understanding ",\t\n\r
of concepts and");
practical
whileFor(tokens.hasMoreTokens()){
techniques.
experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
houses_in_awahtukee.add(
application development.

Double.valueOf(tokens.nextToken()));
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise
Applications with Jython covers important topics such as:
}

}
Fundamental programming
concepts, including statements, expressions,
catch(Exception
e){
interpreters, and compilers
e.printStackTrace();
}
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions

HashMap report =
Stats.reportStatistics(houses_in_awahtukee);
Object-oriented programming concepts
HashMap ranges = (HashMap)report.get("ranges");
HashMap File
averages
input/output=
(HashMap)report.get("averages");
Python's
intrinsic=functions
Object []
m_args
new Object[]{
averages.get("mean"),
Formatting, parsing, and manipulating strings
averages.get("mode"),
averages.get("median")} ;
Interfacing with the Java APIs and working with Java Streams

Object []
r_args
= Java
newSwing
Object
[]{
Using
Python and
to create
GUIs
ranges.get("min"),
ranges.get("max"),
Working with SQL and JDBC(TM)
ranges.get("range")} ;
Python and Java applets

System.out.println(
In addition, the book contains instructions for downloading and installing the Python
MessageFormat.format(range_format,r_args));
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
System.out.println(

MessageFormat.format(average_format,m_args));
}
}

Whether you are a sophisticated computer user new to programming or a serious


application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

Embedding Jython in Java

777

What follows is an example of embedding Jython in the Java code that ships with Jython's standard distribution.

I've added comments.


Python Programming

with the Java Class Libraries: A Tutorial for Building


Web and Enterprise Applications with Jython
org.python.util.PythonInterpreter;
By Richard Hightower

import
import org.python.core.*;

Publisher: Addison Wesley

public class SimpleEmbedded


{
Pub Date: June 28, 2002
public static void main(String []args) throws PyException {

Table of
Contents//

ISBN: 0-201-61616-5

Pages: 640

Create a Python interpreter.


PythonInterpreter interp = new PythonInterpreter();

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
System.out.println("Hello, brave new world");
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
// Execute an import statement and a
application development.

// print statement.
interp.exec("import
sys");
This tutorial begins with coverage
of some of the basics of Python programming. Using
interp.exec("print
sys");
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical

// Create
variable
by assigning
techniques.aFor
experienced programmers,
the book demonstrates Python's breadth of
// it
the value
42.
capabilities
and shows
the ways that Python interfaces with Java APIs for professional
// PyInterger
is a Python integer.
application development.
interp.set("a", new PyInteger(42));
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web

// Execute
the
print with
statement
toimportant topics such as:
and Enterprise
Applications
Jython covers
// print out the value of a.
interp.exec("print a");
Fundamental programming concepts, including statements, expressions,
interpreters,
compilers
// Assign
x to and
equal
the expression 2 + 2.

interp.exec("x = 2+2");

Python basics, including operators, string formatting, namespaces, classes, errors,


and exceptions
// Get the
value associated with x.

PyObjectObject-oriented
x = interp.get("x");
programming concepts
// PrintFilethe
value of x.
input/output
System.out.println("x: "+x);
}

Python's intrinsic functions

}
Formatting, parsing, and manipulating strings
The preceding example doesn't do justice to the true ease of Java-Jython integration.
Interfacing with the Java APIs and working with Java Streams

CONTENTS

Using Python and Java Swing to create GUIs


Working with SQL and JDBC(TM)
Python and Java applets
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
CONTENTS
Web and Enterprise Applications with Jython
By Richard Hightower

Appendix E. Publisher:
Regular
Expressions
Addison Wesley
Pub Date: June 28, 2002

A Simple Example
ISBN: 0-201-61616-5
Table of
Pattern Characteristics
Pages: 640
Contents
Regular Expression Functions and Error and Flags Properties
Characterized
by ease of use, richness of expression, and concise syntax, Python has
re Object Methods
and Properties
remained a premier programming language for more than a decade, and is used by
Match Object Methods and Properties
novices and professionals alike. In particular, its close relationship to Java(TM) makes
Metacharacters
the two languages, when used in combination, ideal for Web and distributed enterprise
Putting Things
Together
application
development.

Jaysen Lorenzen

This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
Regular expressions help
are patterns
thattomatch
groups ofdevelop
characters.
We can use them
to find and
(or replace)
those new
programming
an understanding
of concepts
andreturn
practical
characters, words, and
lines.
Python's
standard-distribution
re
module
derives
from
Perl's
regular
expressions,
techniques. For experienced programmers, the book demonstrates Python's breadth of
which, like Perl itself,
combine features
from
utilities
suchinterfaces
as Awk, Sed,
programs like vi
capabilities
and shows
theUNIX
ways that
Python
with and
JavaGrep,
APIs and
for professional
and Gnu Emacs. Though
the
syntax
and
metacharacters
may
be
slightly
different,
expressions
in
any of these
application development.
tools can be written in Jython.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
A Simple Example
Let's say that you're lookingFundamental
for a job in the
newspaper concepts,
and you'veincluding
decided to
narrow your
focus to ads that say,
programming
statements,
expressions,
"Money is no object." Thisinterpreters,
is the patternand
you're
searching
for,
and
of
course
you're
looking
in the employment
compilers
section, which is the group of characters you're searching in. You don't care where you find your pattern, only
Python basics, including operators, string formatting, namespaces, classes, errors,
that it's there.
and exceptions
If you were writing a Python program to help you find a job, it would start out looking like this:
Object-oriented programming concepts

>>> from re import *


File input/output
mino = compile("money
is no object");
Python's intrinsic functions
for ad in classifieds:
if(mino.search(ad)):
print ad;Formatting, parsing, and manipulating strings
Interfacing with the Java APIs and working with Java Streams
Let's work through this example interactively.
Import the re module.

Using Python and Java Swing to create GUIs

Working
>>> from re import
* with SQL and JDBC(TM)
Import class re.

Python and Java applets

In addition,
the book contains
instructions
for downloading
and installing the Python salary money
>>> classifieds
= ["School
Teacher;
salary
$20,000.","Engineer;
language
and
the
Java
Development
Kit
(JDK).
Terminology,
definitions, explanations,
is no object"]
and numerous code samples make this book a useful learning experience.
Make the variable classifieds a list of ads.
Whether you are a sophisticated computer user new to programming or a serious
application developer, is
Python
>>> mino = compile("money
noProgramming
object")with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.
Compile the search phrase, and store in it the mino ("money is no object") object.

777

>>> for ad in classifieds:


...
if(mino.search(ad)):

...
...

print
ad
Python
Programming
with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

Compare the precompiled expression to each element in the list. If a match is found within an element, print it.
Publisher: Addison Wesley

'Engineer; salary money is no object'


Pub Date: June 28, 2002
>>>

Table of
Contents

ISBN: 0-201-61616-5
Pages: 640

Pattern Characteristics
Characterized by ease of use, richness of expression, and concise syntax, Python has
remained
a premier
programming
language
for morematching
than a decade,
and is
by any
A pattern can be as small
as one
character
(as in the previous
example),
only itself,
orused
of almost
novices
and
professionals
alike.
In
particular,
its
close
relationship
to
Java(TM)
makes
length. It can contain wildcard and special characters, subexpressions, and so forth, depending on system
the
two
languages,
when
used
in
combination,
ideal
for
Web
and
distributed
enterprise
resources.
application development.
Our expression "money is no object" is a string of literal characters requiring an exact match in the exact order,
Thiscan
tutorial
begins
with
coverage
of some
of the basics
of Python
programming.
Usingsalary
but regular expressions
be much
more
powerful.
Say,
for example,
that you're
looking
for a job whose
plenty
of
skill-building
exercises
and
interactive
programming
sessions,
this
book
willall
figure is within a certain rangethat is, with a certain number of digits to the left of the decimal. To find
help
those
new
to
programming
develop
an
understanding
of
concepts
and
practical
records with two digits before the comma and three digits after, you can write this expression:
techniques. For experienced programmers, the book demonstrates Python's breadth of
>>> reStr = r'\$..,...\.'
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
Then you can compile and match it against a string.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
>>> cre = compile(reStr)
and Enterprise Applications with Jython covers important topics such as:

>>> cre.search("salary: $90,000.00")

The figure $90,000 matches,


and the statement
returns concepts,
a match object.
Fundamental
programming
including statements, expressions,
interpreters, and compilers

The Raw String Construct

Python basics, including operators, string formatting, namespaces, classes, errors,


and exceptions
Notice the r'...' construct in the code above. This denotes a raw stringthat is, one with its backslash (\)
escaped characters left intact.
In this case the
$ and the decimal
are the special characters that must be escaped
Object-oriented
programming
concepts
to be matched with a wildcard or metacharacter.
File input/output
Actually, the pattern above would work without the raw string construct, but I wanted to introduce it early on
because its absence can occasionally
cause problems,
Python's intrinsic
functions as you can see in the following examples.
The following expression, Formatting,
with r'...'
, returns
match:
parsing,
anda manipulating
strings

>>> STR = r'(\be[Interfacing


a-z][ with
a-z])'
the Java APIs and working with Java Streams
>>> cre = compile(STR)
>>> cre.search("the
end")
Using beg
Pythonthe
and Java
Swing to create GUIs
Its matched text is end, gotten
withwith
group
Working
SQL. and JDBC(TM)

>>> cre.search("the
theapplets
end").group()
Pythonbeg
and Java
'end'
In addition, the book contains instructions for downloading and installing the Python
This one, without r'...'
, doesn't
a match:
language
and theget
Java
Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.

>>> STR = "(\be[ a-z][ a-z])"


>>> cre = compile(STR)
Whether you are a sophisticated computer user new to programming or a serious
>>> cre.search("the
beg thePython
end")
application developer,
Programming with the Java(TM) Class Libraries will
>>>
give you insight into the power of Python and the know-how to put it to work.
A look at the two expressions' patterns shows why. Here's the first one:

777

>>> STR = r'(\be[ a-z][ a-z])'

>>> cre = compile(STR)


Python Programming with the Java Class Libraries: A Tutorial for Building
>>> cre.pattern
Web and Enterprise Applications with Jython
By Richard Hightower

which returns
Publisher: Addison Wesley

'(\\be[ a-z][ a-z])'

Pub Date: June 28, 2002

Here'sTable
the second
one:
of

Contents

ISBN: 0-201-61616-5
Pages: 640

>>> STR = "(\be[ a-z][ a-z])"


>>> cre = compile(STR)
Characterized by ease of use, richness of expression, and concise syntax, Python has
>>> cre.pattern
remained a premier programming language for more than a decade, and is used by
which returns

novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.

'(\be[ a-z][ a-z])'

This tutorial begins with coverage of some of the basics of Python programming. Using
The lesson is, use theplenty
raw string
construct whenever
normal
string might
cause confusion.
can't
hurt.
of skill-building
exercisesaand
interactive
programming
sessions, Itthis
book
will
help those new to programming develop an understanding of concepts and practical

Wildcard Metacharacters
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
development.
In regular expressionapplication
patterns, the
period is a wildcard, that is, a special character that by default matches any
character except a newline (\n). In our example, '\$..,...\' says in English, A dollar sign followed by
PythonaProgramming
with by
theaJava(TM)
Class
Libraries:
A Tutorialcharacters
for Building
any two characters, except
newline, followed
comma, then
any
three non-newline
andWeb
a
and
Enterprise
Applications
with
Jython
covers
important
topics
such
as:
period. Thus, $XX,XXX or $00,000 or even a dollar sign and six spaces makes a match. Of course, this isn't
very useful, so we have to narrow our search. One way to do this is with a character class instead of a
metacharacter.
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers

Character Classes

Python basics, including operators, string formatting, namespaces, classes, errors,


exceptionsenclosed in brackets, only one of which is required for the sequence to
A character class is a groupand
of characters
match. In our salary example, each period can be replaced with a class of numbers such as [0123456789],
which gets the job done butObject-oriented
is hard to read.programming
Fortunately, aconcepts
class can contain a range of characters expressed as
[0-9], which makes for easier reading.
File input/output

r'\$[0-9][0-9],[0-9][0-9][0-9]\.'
Python's intrinsic functions

This is still a bit unwieldy. Read on.


Formatting, parsing, and manipulating strings

Escaped Special Characters


Interfacing with the Java APIs and working with Java Streams
Usinghave
Python
and Java
SwingThe
to create
GUIs for example, matches any decimal
A number of escaped characters
special
meaning.
\d character,
digit and is equal to [0-9], so our expression can be written as
Working with SQL and JDBC(TM)

r'\$\d\d,\d\d\d\.'

Python and Java applets

Easier still, but wait, there's more.


In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
Multiplier Characters
and numerous code samples make this book a useful learning experience.

are a sophisticated
computer
new toleft.
programming
or a serious
Multiplier charactersWhether
modify, you
or multiply,
the character
to their user
immediate
The most popular
(and sometimes
developer,
Python
Programming
Java(TM)toClass
will
the most dangerous)application
is the asterisk
(*), which
requires
0 or more with
of thethe
characters
its leftLibraries
to produce
a match.
insight into
power ofsoPython
andanother
the know-how
to +,
putwhich
it to work.
In our case, all of thegive
digityou
characters
are the
mandatory,
we need
multiplier,
matches one or
more of the characters to its right. Now our expression can be written as

777

r'\$\d+,\d+\.'

This is shorter and easier,


butProgramming
we still have a with
problem.
The + character
matches one
or morefor
of the
preceding
Python
the Java
Class Libraries:
A Tutorial
Building
characters, which means
salary such Applications
as $9999,99999
would
be caught in its net. To avoid this, we use the
Webthat
andaEnterprise
with
Jython
sequence{min,max}
, whichHightower
requires at least min and no more than max repetitions of the character to the
By Richard
immediate left to produce a match.
Publisher: Addison Wesley

Our expression can nowPub


be written
precisely as
Date: June 28, 2002
ISBN: 0-201-61616-5
r'\$\d{2,2},\d{3,3}\.'
Table of

Contents

Pages: 640

The only remaining problem is that we'll get salaries as low as $00,000 and as high as $99,999, but we can fix
Characterized
byback
ease to
of ause,
richness
of expression,
concise
syntax,
Python
hasour
this by converting part
of our pattern
character
class
containing aand
more
sensible
range.
Finally,
remained
a
premier
programming
language
for
more
than
a
decade,
and
is
used
by
expression can be written as
novices and professionals alike. In particular, its close relationship to Java(TM) makes
r'\$[5-7]\d,\d{3,3}\.'
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
which allows salaries only in the range of $50,000 to $79,000.
This tutorial begins with coverage of some of the basics of Python programming. Using
of skill-building exercises and interactive programming sessions, this book will
Grouping andplenty
Backreferences
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
A very useful feature of Python regular expressions is their ability to reference (or "backreference") text
capabilities and shows the ways that Python interfaces with Java APIs for professional
previously matched and reuse it. Suppose we're looking for a salary in the range of $XX,XXX,XXX. We can
application
extend our expression
by addingdevelopment.
another set of \d{3,3}, but, since we already have this written, we can reuse
it instead. To capture the pattern we use the (...) sequence.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
r'\$[5-7]\d(,\d{3,3})\.'
The piece enclosed in parentheses
is called
a group or aconcepts,
subexpression.
Westatements,
can use it to
add another three digits
Fundamental
programming
including
expressions,
to our search.
interpreters, and compilers
Groups are referenced within
the expression
by theiroperators,
numeric position
and escaped
by a backslash.
The
group
Python
basics, including
string formatting,
namespaces,
classes,
errors,
numbers are determined byand
a count
of
the
open
parentheses
starting
from
the
left:
(1
)(2
)(3
(4
)).
Now
we
can
exceptions
extend our expression like so:
Object-oriented programming concepts

r'\$[5-7]\d(,\d{3,3})\1\.'

File input/output
The\1 gives us another set of ,\d{3,3} , and our expression thus matches our chosen range.
Python's intrinsic functions

The Match ObjectA Brief Introduction

Formatting, parsing, and manipulating strings

In Python, when a match is found a match object is returned. The match object and its properties will be dealt
Interfacing with the Java APIs and working with Java Streams
with later, but we'll give it a brief look here.

Using Python and Java Swing to create GUIs


Here's our salary example compiled and matched against the list of classifieds, now with some added records
and capturing the match object
for later
Working
withuse.
SQL and JDBC(TM)

>>> from re import


* and Java applets
Python
>>> classifieds
= ["School
Teacher;
salary
$20,000.","Engineer;
In addition,
the book contains
instructions
for downloading
and installing the Python salary money
is no object","Bicycle
Racer;
salary
language and the Java
Development
Kit $75,000,000."]
(JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.

>>> for ad in classifieds:


you are a sophisticated computer user new to programming or a serious
...
mo = Whether
mino.search(ad)
application developer, Python Programming with the Java(TM) Class Libraries will
...
if mo:
give you insightprint
into the power
...
ad of Python and the know-how to put it to work.
...
print mo.group(1)
...

777

The output is the ad in which the match was found on the first line and only the text matched by group 1 on the

second line.

Bicycle
,000

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
Racer;
salary
$75,000,000.
By Richard
Hightower
Publisher: Addison Wesley

Alternation

Pub Date: June 28, 2002


ISBN: 0-201-61616-5

Table of
Alternation,
which requiresPages:
the special,

640 or meta-, sequence ...|..., works in any type of expression in which


Contents
the character class operates only with literal characters or ranges. Within a pattern, characters, classes, groups, or
special characters separated
by a bar
need
item of
from
either side
to concise
match. syntax, Python has
Characterized
by(|)ease
of only
use, one
richness
expression,
and
remained a premier programming language for more than a decade, and is used by
a|b|c|d matches
a and
orprofessionals
b or c or
novices
alike.dIn particular, its close relationship to Java(TM) makes
abc|xyz matches
abc
or xyz
the two
languages,
when used in combination, ideal for Web and distributed enterprise
123|[123] matches
123
or 1 or 2 or 3
application
development.

Within a longer expression,


the alternation
sequence
is of
used
likeofthis:
This tutorial
begins with
coverage
some
the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
"(thousands|tons)
of copies"
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
which matches "thousands of copies" or "tons of copies."
capabilities and shows the ways that Python interfaces with Java APIs for professional
application
development.
We can use alternation
to enhance
our salary pattern by allowing numbers in the range $50,000,000 to
$79,999,999 or in the range $50,000,000,000 to $79,999,999,999. All we have to do is replace the \1 with
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
(\1|\1\1).
and Enterprise Applications with Jython covers important topics such as:

r'\$[5-7]\d(,\d{3,3})(\1|\1\1)\.'

Regular

Fundamental programming concepts, including statements, expressions,


interpreters,
and compilers and Error and Flags Properties
Expression
Functions

Python basics, including operators, string formatting, namespaces, classes, errors,


The following sections describe the individual regular expression functions, including their syntax, use,
and exceptions
arguments, and return values. Also described are the error and flag properties.
Object-oriented programming concepts

compile()
File input/output

compile (pattern[, flags])

Python's intrinsic functions


Thecompile() function compiles a regular expression pattern, as a string, into a regular expression object. It
Formatting,
parsing, andand
manipulating
enables the object to operate
like the search()
match()strings
functions and to be reused for subsequent
searches. If the same expression
is
applied
to
many
searches
within
a program
and/or
will never change,
Interfacing with the Java APIs and working
with Java
Streams
precompiling it and reusing it goes faster.
Using Python and Java Swing to create GUIs
compile()'s arguments are
Working with SQL and JDBC(TM)

pattern the pattern,


as a string, to search for
Python and Java applets
flags oneInoraddition,
more of the following variables: I,IGNORECASE;L,LOCALE;M,MULTILINE;
the book contains instructions for downloading and installing the Python
X,VERBOSE language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
It returns a regular expression.
Whether
you are a sophisticated computer user new to programming or a serious
>>> CompiledRE
= compile("199[0-9].*")
application
developer, Python
Programming
with the Java(TM) Class Libraries will
>>> CompiledRE.search("party
like
it's 1999")
give you insight into the power of Python and the know-how to put it to work.

search()

777

Search (pattern, string[, flags])

Thesearch() function
searches
for pattern
anywhere
string
. It hasAthe
following
arguments:
Python
Programming
with the
Java in
Class
Libraries:
Tutorial
for Building
Web and Enterprise Applications with Jython
By Richard Hightower

pattern the pattern, as a string, to search for


Publisher: Addison Wesley

string the string to search in

Pub Date: June 28, 2002

ISBN:
0-201-61616-5
flags one or more
of the
variables I,IGNORECASE;L,LOCALE;M,MULTILINE;X,
Table of
Pages:
640
VERBOSE
Contents

Characterized by ease of use, richness of expression, and concise syntax, Python has
It returns a match object:
remained a premier programming language for more than a decade, and is used by
>>> search("199[0-9]$","party
like
it's 1999")
novices and professionals alike.
In particular,
its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
or it returns None, which
meansdevelopment.
the search failed.
application

>>> search("199[0-9]$","party
likeof it's
This tutorial begins with coverage
some of 2009")
the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities
and shows
the ways that Python interfaces with Java APIs for professional
match (pattern,
string[,
flags])
application development.
Thematch() function searches for a pattern at the beginning of a string and has the following arguments:
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:
pattern the pattern, as a string, to search for

match()

string the string


to search inprogramming concepts, including statements, expressions,
Fundamental
interpreters, and compilers

flags one or more of the variables I,IGNORECASE;L,LOCALE;M,MULTILINE;X,


VERBOSE
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
It returns a match object:

Object-oriented programming concepts

>>> match("199[0-9]","1999 like party")


File input/output

or it returns None.

Python's intrinsic functions

>>> match("199[0-9]","party like it's 1999")


Formatting, parsing, and manipulating strings

split()

Interfacing with the Java APIs and working with Java Streams

Split (pattern, string[,


maxsplit
Using Python and
Java Swing=to0])
create GUIs
Thesplit() function splits
a string
intoand
a listJDBC(TM)
of strings based on occurrences of the regular expression
Working
with SQL
pattern. The string portions that don't match the pattern are returned as a list of strings. If flags are required with
the pattern, a regular expression
obtained
with compile(), must be used in place of the pattern string,
Pythonobject,
and Java
applets
or the (?iLmsx) sequences (which will be explained later) must be used within the expression. (The
compiled regular expression's
split()
method will
achieve for
the downloading
same results.)and installing the Python
In addition,
the book contains
instructions
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
split() has the following
arguments:
and numerous
code samples make this book a useful learning experience.

Whether you are a sophisticated computer user new to programming or a serious

patternapplication
the pattern,developer,
as a string,Python
to search
for
Programming
with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

string the string to search in

777

maxsplit the maximum number of splits to make (the default is 0)


It returns a list of strings.

Python
from re import
* Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

alist = split(":","OS=Linux:Browser=Netscape:WM=Afterstep")
Publisher: Addison Wesley
for str in alist:
Pub Date: June 28, 2002
...
print str
Table of

Theoutput
is
Contents

ISBN: 0-201-61616-5
Pages: 640

OS=Linux
Characterized by ease of use, richness of expression, and concise syntax, Python has
Browser=Netscape
remained a premier programming language for more than a decade, and is used by
WM=Afterstep novices and professionals alike. In particular, its close relationship to Java(TM) makes

sub()

the two languages, when used in combination, ideal for Web and distributed enterprise
application development.

tutorial begins with coverage of count


some of the
sub (pattern,This
replacement,string[,
= basics
0]) of Python programming. Using

plenty of skill-building exercises and interactive programming sessions, this book will
thosea string
new towith
programming
develop anoccurrences
understanding
of concepts
andstarting
practical
Thesub() functionhelp
obtains
the non-overlapping
of the
expression,
from the
techniques.
For
experienced
programmers,
the
book
demonstrates
Python's
of
left, replaced by the replacement string. If the optional third argument, count, is supplied, onlybreadth
the requested
capabilities
and
shows
the
ways
that
Python
interfaces
with
Java
APIs
for
professional
number of occurrences is replaced. If flags are required with the pattern, a regular expression obtained with
development.
compile() mustapplication
be used in place
of the pattern string. (The compiled regular expression's sub() method
can achieve the same results.)
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and in
Enterprise
Applications
withstring,
Jython
important
topics
such as:of the pattern, and a
If a function is supplied
place of the
replacement
it'scovers
executed
for each
occurrence
match object is passed as an argument.

sub()'s arguments are Fundamental programming concepts, including statements, expressions,


interpreters, and compilers

Pythonasbasics,
operators,
stringobject,
formatting,
namespaces,
classes, errors,
pattern the pattern,
a stringincluding
or a regular
expression
to search
for
and exceptions

replacement the replacement, as a string or function


Object-oriented programming concepts

string the string to search in


File input/output
count a non-negative number, the number of replacements to make (the default, 0, replaces all
Python's intrinsic functions
occurrences in the string)
Formatting,
strings if there are no matches.
It returns the modified string
if a matchparsing,
is found,and
or manipulating
the original argument

From re import * Interfacing with the Java APIs and working with Java Streams
from string import *
Using Python and Java Swing to create GUIs

def toUpper(matchObj):
Working with SQL and JDBC(TM)
return capitalize(matchObj.group(0))
Python and Java applets

newStr = sub("monkey",toUpper,"monkey see monkey do, ,,")


In addition, the book contains instructions for downloading and installing the Python

print newStr language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
The output is

Whether you are a sophisticated computer user new to programming or a serious

Monkey see Monkey


do,
,, Python Programming with the Java(TM) Class Libraries will
application
developer,
give you insight into the power of Python and the know-how to put it to work.

subn()

777

subn (pattern, replacement,string[, count = 0])

Thesubn() function
is basically
the same as
sub()
exceptClass
that itLibraries:
returns a tuple
containing
the modified or
Python
Programming
with
the Java
A Tutorial
for Building
unmodified string and
the and
number
of replacements
made.with
Its arguments
Web
Enterprise
Applications
Jython are
By Richard Hightower

pattern the pattern, as a string or a regular expression object, to search for


Publisher: Addison Wesley

Date:
June 28, 2002
replacementPub
the
replacement,
as a string or function

Table of
string the
Contents

ISBN: 0-201-61616-5

string
to search
Pages:
640 in

count a non-negative
number
of replacements
to make
(the default,
0,Python
replaceshas
all
Characterizednumber,
by easethe
of use,
richness
of expression,
and concise
syntax,
occurrences inremained
the string)
a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
subn() returns a tuple
containing
the when
modified
if a match isideal
found
theand
original
string argument
the two
languages,
usedstring
in combination,
for(or
Web
distributed
enterprise if
there are no matches)application
and containing
the count of replacements made, if any.
development.

from re import
This*tutorial begins with coverage of some of the basics of Python programming. Using
from string import
*
plenty of skill-building
exercises and interactive programming sessions, this book will
deftoUpper(matchObj):return
help those new to programmingcapitalize(matchObj.group(0))
develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of

tup = subn("monkey",toUpper,"monkey
see interfaces
monkeywith
do,
capabilities and shows the ways that Python
Java,,")
APIs for professional
application development.

print "In \" %s \" there were %s replacements" % tup


The output is

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

In " Monkey see Monkey do, ,, " there were 2 replacements


Fundamental programming concepts, including statements, expressions,
interpreters, and compilers

escape()

Python basics, including operators, string formatting, namespaces, classes, errors,


and exceptions
escape() escapes all nonalphanumeric characters before passing the expression to the compiler, and returns
Object-oriented programming concepts
a string with all metacharacters escaped.

escape(string)

Here's an example in whichFile


theinput/output
compile() function fails because there are unmatched parentheses:

Python's
>>> from re import
* intrinsic functions
>>> strVar = "((group"))
Formatting, parsing, and manipulating strings
>>> cre = compile(strVar)
Interfacing with the Java APIs and working with Java Streams

Traceback (innermost last):


File "<console>",
line
? to create GUIs
Using Python
and1,
Javain
Swing
re.error: Unmatched parentheses.
Working with SQL and JDBC(TM)
In this example, the non-alphanumeric characters are escaped, so the compile() function works:
Python and Java applets

>>> cre = compile(escape(strVar))


In addition, the book
contains instructions
>>> cre.search("((group
1)group
2)") for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
org.python.modules.MatchObject@80cceb1
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.
The error exception is raised when an illegal expression is passed to a function. It has the form

error

try:
...

777

match statement

except error,e:
Python Programming with the Java Class Libraries: A Tutorial for Building
...
handleWeb
the
anderror
Enterprise Applications with Jython
By Richard Hightower

The optional argument to the except statement is a variable to catch the argument sent to the raise
statement at the time of Publisher:
the error. This
can be used in the handler statement to alert the user to a mistake.
Addison Wesley
Pub Date: June 28, 2002
>>> from re import
*
ISBN: 0-201-61616-5
>>> Table
try:of
Pages: 640
... Contents
search("[[[","This
is a test")
... except error,e:
by ease of use, richness of expression, and concise syntax, Python has
...
print Characterized
e
remained
a
premier
programming language for more than a decade, and is used by
...

The output is

novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.

Unmatched [] in expression.
This tutorial begins with coverage of some of the basics of Python programming. Using
>>>
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
flags
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
Thecompile(),search() , and match() functions can take a number of options (or modes). These
application development.
options are set via the functions' optional flags argument and are the same for all. A common example is
IGNORECASE, which
specifies
the matchwith
as case-insensitive.
Thus,
if the ad AlistTutorial
contains
Python
Programming
the Java(TM) Class
Libraries:
for Building Web
and Enterprise Applications with Jython covers important topics such as:

classifieds = ["School Teacher; salary $20,000","Engineer; salary Money is NO


OBJECT"]
Fundamental programming concepts, including statements, expressions,
the expression is written asinterpreters, and compilers

mino = compile("money
is no
object",I)
Python basics,
including
operators, string formatting, namespaces, classes, errors,
or

and exceptions
Object-oriented programming concepts

mino = compile("money is no object",IGNORECASE)


File input/output
The flags available at compile time are listed and described in Table E-1 (on next page).
Python's intrinsic functions
Note that, as of this writing, the LOCALE and VERBOSE flags aren't fully implemented; that is, their values are
set to 0, which is the same Formatting,
as not beingparsing,
set at all.and
You
can get VERBOSE
manipulating
strings functionality by setting the flags
integer to 32 instead of X or VERBOSE, but check your release first, since in CPython this value is 2.
Interfacing with the Java APIs and working with Java Streams

re Object Methods
Using and
Python Properties
and Java Swing to create GUIs
Working
SQLuse,
andand
JDBC(TM)
The sections that follow describe
thewith
syntax,
arguments of regular expression object methods and
properties.
Python and Java applets

search()

In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
<re object>.search
(string[,
and numerous
code samplespos][,
make this endpos])
book a useful learning experience.
Whether
you Optional
are a sophisticated
computer
user
new to programming
or a serious
Table E-1.
Flags for
Regular
Expression
Functions
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Flag

Behavior
Python
Programming with the Java Class Example
Libraries: A Tutorial for Building
Web
and
Enterprise
Applications
with
Jython
I
Ignore case when searching.
search("^exam","Example",I)
(IGNORECASE)ByRichard Hightower
returns a match object
Publisher: Addison Wesley

search("^exam","Example")
returns None

Pub Date: June 28, 2002


The
metacharacters \w,\W,\b,\B are
ISBN:
0-201-61616-5
made
to fit the
currentlocale.
Table of

Pages: 640
M Contents
The metacharacter ^ matches at the
var = "A\nB".
(MULTILINE) beginning of the string and just after each
Characterized
by ease The
of use,
richness of expression, and concise syntax, Python has
newline character.
$ metacharacter
search("^B",var,M)
remained
a
premier
programming
language
than a decade, and is used by
matches at the end of the string
and justfor more
returns a match object
novices
and
professionals
alike.
In
particular,
its
close
relationship to Java(TM) makes
before each newline character (by default
the
two
languages,
when
used
in
combination,
ideal
for
Web and distributed enterprise
^ matches only at the beginning of the
search("^B",var) returns
application
development.
string and $ matches only at the end of
None
the string).
This tutorial begins with coverage of some of the basics of Python programming. Using
S (DOTALL) plenty
The "of
."skill-building
metacharacter
matches
= "A\nB"
exercises
andany
interactivevar
programming
sessions, this book will
character,
including
the
newline.
(The
help those new to programming develop an understanding of concepts and practical
default is for "."to match anything but a search(".B",var,S)
techniques. For experienced programmers, the book
demonstrates Python's breadth of
newline.)
returns
a match
capabilities and shows the ways that Python interfaces
with Java
APIs for object
professional
application development.

L (LOCALE)

search(".B",var)

returnsA Tutorial
None for Building Web
Python Programming with the Java(TM) Class Libraries:
Enterprise
Applications
with Jython covers exp
important
topics such as:
X (VERBOSE) and
Allows
formatting
of the regular
= """
expression. Whitespace within the
# Start of regex
expression is ignored, except when it's in
Fundamental
expressions,
a character
classprogramming
or preceded concepts,
by an including
^t statements,
# starts
with "t"
interpreters,
and compilers
unescaped
backslash.
If a # character is
[a-z] # is a lcase char
inserted, all text from the leftmost # is
* # any
qty of
Python
basics,
including
namespaces, classes, errors,
ignored,
except
when
the # operators,
is within astring formatting,
t$
#
ends
with "t"
and exceptions
character
class or preceded by an
unescaped backslash.
# end of expression
Object-oriented programming concepts
"""
File input/output

regex = compile(exp,X)
regex.search("test")
Returns a match object
Formatting, parsing, and manipulating stringsregex = compile(exp)
regex.search("test")
Interfacing with the Java APIs and working with Java Streams
Returns None
Python's intrinsic functions

Using Python and Java Swing to create GUIs


Thesearch() method looks for compiled regular expressions anywhere in a string. If the optional parameter
pos is supplied, the searchWorking
starts at with
position
If the optional parameter endpos is supplied, the search
SQLpos
and. JDBC(TM)
continues only until endpos is reached. The default is from position 0 to the end of the string. The return value
Python and Java applets
is a match object.

search() has theInfollowing


addition, arguments:
the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
string the string to search in
Whether you are a sophisticated computer user new to programming or a serious
pos the position
in thedeveloper,
string to start
the search
application
Python
Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.
endpos the position in the string to stop the search
Here's an example:

777

cre = compile("199[0-9]$")

cre.search("party
like it's with
1999")
Python Programming
the Java Class Libraries: A Tutorial for Building

match()

Web and Enterprise Applications with Jython


By Richard Hightower

Publisher:
Addison Wesley
<re object>.match
(string[,
pos][, endpos])
Pub Date: June 28, 2002

Thematch()method searches
for0-201-61616-5
a regular expression at the beginning of a string. If the optional parameter
ISBN:
of
pos isTable
supplied,
the searchPages:
starts at
position pos, which is considered the start. If the optional parameter
640
Contents
endpos is supplied, the search ends when endpos is encountered. The default is from position 0 to the end
of the string. The return
is a match by
object.
Characterized
ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
Here's an example that
doesn't
because the
testInisn't
at the beginning
of the string.toTherefore,
novices
andmatch
professionals
alike.
particular,
its close relationship
Java(TM)nothing
makes is
printed out.
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.

>>> cre = compile("test")

This tutorial begins with coverage of some of the basics of Python programming. Using

>>> if (cre.match("This
is exercises
a test")):
plenty of skill-building
and interactive programming sessions, this book will
...
print
help"From
those newbeginning
to programming\n"
develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
Here's an example incapabilities
which the starting
position
is 10.
A match
returned only
theAPIs
expression
is found at the
and shows
the ways
that
Pythonisinterfaces
with if
Java
for professional
beginning of the string.
application development.

>>> if (cre.match("This
is a test",10)):
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
...
print
"From
pos
10 - \n"
and Enterprise Applications with Jython covers important topics such as:

split()

Fundamental programming concepts, including statements, expressions,


and compilers
<re object>.splitinterpreters,
(string[,
maxsplit = 0])
Python
basics,into
including
string
namespaces,
classes, errors,
Thesplit() method splits
a "string"
a list ofoperators,
strings based
on formatting,
the occurrences
of the compiled
regular
and
exceptions
expression to which the string is being compared. The portions of the string that don't match are returned as a list
of strings.
Object-oriented programming concepts

split()'s arguments are

File input/output

Python's
intrinsic
string the string
to search
in functions
Formatting,number
parsing,
manipulating
maxsplit the maximum
ofand
splits
to make (thestrings
default is 0)
Interfacing with the Java APIs and working with Java Streams

Here's an example:

Using
>>> from re import
* Python and Java Swing to create GUIs
Working with SQL and JDBC(TM)

>>> cre = compile(":")

Python and Java applets

>>> alist = cre.split("OS=Linux:Browser=Netscape:WM=Afterstep")


In addition, the book contains instructions for downloading and installing the Python

>>> for str in


alist:
language
and the Java Development Kit (JDK). Terminology, definitions, explanations,
...
print
str
and numerous
code samples make this book a useful learning experience.
The output is

Whether you are a sophisticated computer user new to programming or a serious


application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

OS=Linux
Browser=Netscape
WM=Afterstep

sub()

777

Python Programming with the Java Class Libraries: A Tutorial for Building
<re object>.sub
(replacement,string[, count = 0])
Web and Enterprise Applications with Jython
By Richard Hightower

Thesub() method achieves the same result as the sub() function described previously and has the same
arguments (except pattern). Unlike the sub() function, however, which returns a list of strings, the
Addison
sub() method returnsPublisher:
the modified
stringWesley
if a match is found, or the original string argument if there are no
Pub
Date:
June
28,
2002
matches.
Table of

ISBN: 0-201-61616-5

>>> Contents
from re import
* 640
Pages:
>>> from string import *
Characterized by ease of use, richness of expression, and concise syntax, Python has

>>> def toUpper(matchObj):


remained a premier programming language for more than a decade, and is used by
...
return
capitalize(matchObj.group(0))
novices
and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise

cre = compile("monkey")
application development.
newStr = cre.sub(toUpper,"monkey see monkey do, ,,")
This tutorial begins with coverage of some of the basics of Python programming. Using
print newStr plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
The output is
capabilities and shows the ways that Python interfaces with Java APIs for professional
Monkey see Monkey
do,
,,
application
development.

subn()

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

<re object>.subn (replacement,string[, count = 0])


Fundamental programming concepts, including statements, expressions,
Thesubn() method performs similarly to the subn() function described previously. As shown in the
interpreters, and compilers
following example, it uses the same arguments (except for pattern) and returns a tuple.
Python basics, including operators, string formatting, namespaces, classes, errors,

from re import * and exceptions


from string import *

Object-oriented programming concepts

def toUpper(matchObj):
return capitalize(matchObj.group(0))
File input/output
Python's intrinsic functions
cre = compile("monkey")
tup = cre.subn(toUpper,"monkey see monkey do, ,,")
Formatting, parsing, and manipulating strings

print "In \" %s \" there were %s replacements" % tup

Interfacing with the Java APIs and working with Java Streams

The output is

Using Python and Java Swing to create GUIs

In " Monkey see Monkey do, ,, " there were 2 replacements


Working with SQL and JDBC(TM)

flags

Python and Java applets

addition,
bookthat
contains
instructions
andtoinstalling
the Python
Theflags propertyIncontains
anthe
integer
represents
the sumfor
ofdownloading
all flags passed
the compile()
language
and
the
Java
Development
Kit
(JDK).
Terminology,
definitions,
function when the object was created, or 0 if no flags were passed. It can be used to determine explanations,
if a certain set of
code of
samples
this book
a useful learning
experience.
flags was passed andand
cannumerous
take the place
flagmake
arguments
to subsequent
compile()
,search() , or
match() function calls.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

Finding a Flag Value

Addison
You can create aPublisher:
match object
for a Wesley
flag to check its property value (do this one flag at a time; if
Date:
28, 2002
you try with morePub
than
one,June
the value
becomes their sum). Or you can check the underlying object's
flag property value,ISBN:
which
is the only way to check VERBOSE since
0-201-61616-5
Table of
compile("test",VERBOSE).flags
or compile("test",VERBOSE) returns 0.
Pages: 640
Contents

To check the Characterized


underlying values,
import
the richness
Perl5Compiler
and check
the properties
by ease
of use,
of expression,class,
and concise
syntax,
Python has
like this:
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
>>> from the
com.oroinc.text.regex
import Perl5Compiler
two languages, when used in combination, ideal for Web and distributed enterprise
application development.

>>>
1
>>>
8
>>>
16
>>>
32

Perl5Compiler.CASE_INSENSITIVE_MASK

This tutorial begins with coverage of some of the basics of Python programming. Using

Perl5Compiler.MULTILINE_MASK
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical

Perl5Compiler.SINGLELINE_MASK
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional

Perl5Compiler.EXTENDED_MASK
application development.

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise
Applications
Jython
coversused
important
such
as: was created, or 0
flags returns an integer
that represents
the sumwith
of all
flag values
at the topics
time the
object
if no flags were used.

>>>
>>>
1
>>>
8
>>>
9
>>>
16
>>>
24
>>>
>>>
>>>
24

Fundamental
programming concepts, including statements, expressions,
from re import
*
interpreters, and compilers
compile("^f",I).flags
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions

compile("^f",M).flags

compile("^f",I|M).flags
Object-oriented programming concepts
compile("^f",S).flags
File input/output
Python's intrinsic functions
compile("^f",M|S).flags
Formatting, parsing, and manipulating strings

cre = compile("^f",M|S)
Interfacing with the Java APIs and working with Java Streams
compile("g$",cre.flags).flags
Using Python and Java Swing to create GUIs

groupindex

Working with SQL and JDBC(TM)

Python and Java applets


<re object>.groupindex
addition,
thea book
contains
instructions
for downloading
and installing
the Python
ThegroupindexIn
property
gets
dictionary
of the
group numbers
of the expression
that creates
the regular
language
and
the
Java
Development
Kit
(JDK).
Terminology,
definitions,
expression object, with their symbolic group names as the key, if the groups were created with explanations,
the (?
and numerous
code
samples
make or
thisanbook
a useful
learning experience.
P<key>...) construct.
It returns
such
a dictionary
empty
dictionary.

>>>
>>>
>>>
>>>
1
>>>

Whether you
from re import
* are a sophisticated computer user new to programming or a serious
application
developer, Python Programming with the Java(TM) Class Libraries will
cre = compile(r'(?P<first>est)(?P<last>t)')
give
you
insight
into the power of Python and the know-how to put it to work.
dict = cre.groupindex
dict["first"]

777

dict["last"]

The output is

{}

Python Programming with the Java Class Libraries: A Tutorial for Building
Web and Enterprise Applications with Jython
By Richard Hightower

pattern

Publisher: Addison Wesley


Pub Date: June 28, 2002

<re object>.pattern
ISBN: 0-201-61616-5

Table of

Pages: 640

Contents
Thepattern
property contains the expression, that is, the pattern string, with which the regular expression
object was created. ItCharacterized
returns a string
regular expression.
bycontaining
ease of use,a richness
of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
>>> from re import
*
novices and professionals alike. In particular, its close relationship to Java(TM) makes
>>> cre = compile("^t.+t$")
the two languages, when used in combination, ideal for Web and distributed enterprise
>>> cre.pattern
application development.

The output is

This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
'^t.+t$'
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
Match Object
Methods
and
Properties
capabilities
and shows
the ways
that Python interfaces with Java APIs for professional
application development.
The following sections describe the methods and properties of the match object.
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

group()

Fundamental programming concepts, including statements, expressions,


<match object>.group([name|num][,name|num]...)
interpreters, and compilers
Thegroup() method gets matches of each group of the expression, or all matches if no group is specified. If
Python
basics,
including
operators,
string
namespaces,
classes, errors,
a single argument is passed,
the return
value
is a string
containing
theformatting,
group specified.
If no arguments
are
and
exceptions
passed, the return value is a string containing the entire match. If a group is in part of a pattern that doesn't
match, the return value is None. If it's in part of the pattern that matches multiple times, the last match is
Object-oriented programming concepts
returned.
File input/output
>>> mo = search(r'(?P<first>t)(?P<last>est)',"test")
>>> mo.group()
Python's intrinsic functions
'test'
>>> mo.group("first")
Formatting, parsing, and manipulating strings
't'
>>> mo.group("last")
Interfacing with the Java APIs and working with Java Streams
'est'
>>> mo.group(2) Using Python and Java Swing to create GUIs
'est'
Working with SQL and JDBC(TM)
The return is a tuple.

Python and Java applets

>>> mo.group("first","last")
('t', 'est') In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
>>>
and numerous code samples make this book a useful learning experience.

groups()

Whether you are a sophisticated computer user new to programming or a serious


application developer, Python Programming with the Java(TM) Class Libraries will
<match object>.groups()
give you insight into the power of Python and the know-how to put it to work.
Thegroups() method returns a tuple containing all matched text for all groups of the pattern, including
those that don't match. Elements in the tuple representing groups that don't match have a value of None.

777

>>> mo = search(r'(?P<first>t)(?P<last>est)+(o)*',"test")

>>> mo.groups()
Python Programming with the Java Class Libraries: A Tutorial for Building
('t', 'est', Web
None)
and Enterprise Applications with Jython
>>>
By Richard Hightower

groupdict()

Publisher: Addison Wesley


Pub Date: June 28, 2002

ISBN: 0-201-61616-5
<match
object>.groupdict()
Table of

Pages: 640

Contents

Thegroupdict() method returns a dictionary containing all matched text for all groups of the pattern,
including those that Characterized
don't match. Elements
in use,
the dictionary
a value
by ease of
richness ofrepresenting
expression, unmatched
and concisegroups
syntax,have
Python
has of
None.
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
>>> mo = search(r'(?P<first>t)(?P<last>est)+(o)*',"test")
the two languages, when used in combination, ideal for Web and distributed enterprise
>>> dict = mo.groupdict()
application development.

>>> print dict["first")


This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
start() and end()
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
<match object>.start([name|num])
capabilities and shows the ways that Python interfaces with Java APIs for professional
<match object>.end([name|num])
application development.
Thestart() and end() methods retrieve the starting and ending positions of the groups matched within the
Python
Programming
withcan
thebeJava(TM)
Class Libraries:
Tutorial
for of
Building
Web
string being searched.
The optional
argument
a group number
(countingAfrom
the left
the expression)
and
Enterprise
Applications
with
Jython
covers
important
topics
such
as:
or a name if the group was named at the time of creation. If no arguments are passed, the start and end positions
are the start and end of the entire matched text. The return value for both methods is an integer.

>>>
>>>
0
>>>
1
>>>
1
>>>
4
>>>
-1

Fundamental programming concepts, including statements, expressions,

mo = search(r'(?P<first>t)(?P<last>est)+(o)*',"test")
interpreters, and compilers
mo.start(1)

Python basics, including operators, string formatting, namespaces, classes, errors,

mo.start(2) and exceptions

mo.start("last")
Object-oriented programming concepts
File input/output
mo.end("last")

mo.start(3) Python's intrinsic functions


Formatting, parsing, and manipulating strings

>>> mo.start()
0
>>> mo.end()
4

Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs
Working with SQL and JDBC(TM)

span()

Python and Java applets

<match object>.span([name|num])
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
Thespan() method returns the starting and ending positions of a matching group as a two-element tuple. The
and numerous code samples make this book a useful learning experience.
optional argument is a group number (starting from the left of the expression). If no argument is passed, the tuple
will contain the startWhether
and end you
positions
the entire matched
text.
If new
the group
doesn't match
all, the tuple will
are a of
sophisticated
computer
user
to programming
or aatserious
contain1,1.
application developer, Python Programming with the Java(TM) Class Libraries will

>>>
>>>
(0,
>>>

give you insight into the power of Python and the know-how to put it to work.

mo = search(r'(?P<first>t)(?P<last>est)+(o)*',"test")
mo.span(1)
1)
mo.span(2)

777

(1, 4)
Python Programming with the Java Class Libraries: A Tutorial for Building
>>> mo.span(3)
Web and Enterprise Applications with Jython
(-1, -1)
By Richard Hightower

pos and endposPublisher: Addison Wesley


Pub Date: June 28, 2002
ISBN: 0-201-61616-5
<match
object>.pos
Table of

Contents

Pages: 640

<match object>.pos
Characterized by ease of use, richness of expression, and concise syntax, Python has
Thepos property returns
the pos
value,programming
as an integer,language
passed tofor
themore
search()
or match()
method.
The
remained
a premier
than a decade,
and is used
by
endpos property returns
endpos
value,alike.
as anIn
integer,
passed
those
methods. to Java(TM) makes
novicesthe
and
professionals
particular,
its to
close
relationship
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
string
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help
those the
newstring,
to programming
an understanding
ofthe
concepts
and practical
Thestring property
returns
as a string todevelop
be searched
and passed to
search()
or
techniques.
For
experienced
programmers,
the
book
demonstrates
Python's
breadth of
match() method.
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.

<match object>.string

re

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web

<match object>.re
and Enterprise Applications with Jython covers important topics such as:
There property gets a reference to the regular expression object from which the match was triggered. It returns
a regular expression object.Fundamental programming concepts, including statements, expressions,
interpreters, and compilers

>>> from re import *


including operators, string formatting, namespaces, classes, errors,
# from a standardPython
re basics,
object
and
exceptions
>>> cre = compile(r'(?P<first>t)(?P<last>est)+(o)*')
Object-oriented programming concepts
>>> mo.re.groupindex
{'last': 2, 'first': 1}
File input/output

# Retrieve the rePython's


object
from
the search function.
intrinsic
functions
>>> mo = search(r'(?P<first>t)(?P<last>est)+(o)*',"test")
Formatting, parsing, and manipulating strings
>>> mo.re
org.python.modules.RegexObject@80ce6f2
Interfacing with the Java APIs and working with Java Streams
Using Python and Java Swing to create GUIs
>>> mo.re.groupindex
{'last': 2, 'first': 1}
Working with SQL and JDBC(TM)

>>> mo.re.pattern
Python and Java applets
'(?P<first>t)(?P<last>est)+(o)*'
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
Metacharacters
and numerous code samples make this book a useful learning experience.
The Python metacharacters,
special
andcomputer
sequences,
arenew
listed
described in
E2 and E-3.
Whetheroryou
are acharacters
sophisticated
user
toand
programming
or Tables
a serious

application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.
Table E-2. Python Metacharacters (Single Characters)

777

Metacharacter Behavior

Example

" ."

Matches
character except
a newline,
by Libraries:
search(".B","AB")
Python any
Programming
with the
Java Class
A Tutorial for Building
default.
If the
DOTALLApplications
flag has been
specified,
Web and
Enterprise
with
Jython returns a match object
this
matchesHightower
any character, including a newline.
By Richard
Publisher: Addison Wesley

" ^"

" $"

" *"

Table of
Contents

search(".B","A\nB")
returns None
search("^cat","cats")
returns a match object

Pub Date:
28, 2002
Matches
at theJune
beginning
of a string and, if the
MULTILINE
is used, also matches
ISBN: flag
0-201-61616-5
immediately
after
Pages:
640each newline. Used as the first
character of the expression or group to match at search("^cat","a cat")
the
beginning ofbya ease
string.
Characterized
of use, richness of expression, returns
and concise syntax,
Non Python has
remained
a
premier
programming
language
for
more
than
a
decade,
and is used by
Matches at the end of a string and, if the
search("at$","cat")
novices
and
professionals
alike.
In
particular,
its
close
relationship
to
Java(TM)object
makes
MULTILINE flag is used, also matches
returns a match
the
two
languages,
when
used
in
combination,
ideal
for
Web
and
distributed
enterprise
immediately before each newline. Used as the
application
last
characterdevelopment.
of the expression or group to
search("at$","cats")
match at the end of a line.
returns None
This tutorial begins with coverage of some of the basics of Python programming. Using
Matches
or more repetitions
of interactive
the
cre = compile("at*")
plenty ofzero
skill-building
exercises and
programming
sessions, this book will
preceding
character,
group,
or
character
class.
help those new to programming develop an understanding of concepts and practical
None of the immediately preceding characters is cre.search("a")
techniques. For experienced programmers, the book demonstrates Python's breadth of
required to match, and any number of the
cre.search("at")
capabilities and shows the ways that Python interfaces
with Java APIs for professional
immediately preceding characters will match. A cre.search("att")
application
development.
greedy
multiplier,
"*" will match as many

repetitions as possible.
cre A=Tutorial
compile("a[td]*")
Python Programming with the Java(TM) Class Libraries:
for Building Web
cre.search("atdt")
and Enterprise Applications with Jython covers important
topics such as:

cre = compile("A(BC)*")
Fundamental programming concepts, includingsearch("ABCBC")
statements, expressions,
interpreters, and compilers
all return a match

search("e[td]*","add")

" +"

Python basics, including operators, string formatting,


classes,
does namespaces,
not return
a errors,
match
and exceptions
Matches one or more repetitions of the
cre = compile("at+")
preceding
character,
group,
or
character
class.
cre.search("at")
Object-oriented programming concepts
Atleast one of the immediately preceding
cre.search("att")
characters
groups of characters is required to
File or
input/output
match, and any number of the them will match. A cre = compile("a[td]+")
greedy multiplier,
"+" willfunctions
match as many
Python's intrinsic
cre.search("atdt")
repetitions as possible.
cre = compile("A(BC)+")
Formatting, parsing, and manipulating strings search("ABCBC")
Interfacing with the Java APIs and working with Java Streams

all return a match

Using Python and Java Swing to create GUIs

" ?"

cre = compile("at+")
cre.search("a")
Working with SQL and JDBC(TM)
does not return a match
Python
and
Java
applets
Matches zero or one repetition of the preceding var = compile("xa?bc")
character, group, or character class. None of the
In addition, preceding
the book contains
instructions
for downloading
and installing the Python
immediately
characters
or groups
of var.search("xbc")
language
and
the
Java
Development
Kit
(JDK).
Terminology,
definitions, explanations,
characters is required to match, and only one of returns
a match object
and
numerous
code
samples
make
this
book
a
useful
learning
experience.
the them will match. A nongreedy multiplier, "?"
will match as few repetitions as possible.
var.search("xaabc")
Whether you are a sophisticated computer user new to
programming or a serious
not
return
match
application developer, Python Programming with thedoes
Java(TM)
Class
Librariesawill
give you insight into the power of Python and the know-how to put it to work.

777

var.search("xabc")
returns a match object

"*?"

Matches
or more repetitions
of the Class Libraries:
cre =A Tutorial
compile("(:.*:)")
Python zero
Programming
with the Java
for Building
preceding
or character
class.
Web andcharacter,
Enterprisegroup,
Applications
with Jython
None
of theHightower
immediately preceding characters is STR = ":one:a:two:"
By Richard
required to match and any number of the
immediately
preceding
characters will match. A mo = cre.search(STR)
Publisher:
Addison Wesley
non-greedy multiplier, "*?" will match as few
mo.group(1)
Pub Date: June 28, 2002
repetitions as possible.
Table of
Contents

ISBN: 0-201-61616-5

Pages: 640

returns
':one:a:two:'

Characterized by ease of use, richness of expression, and concise syntax, Python has
compile("(:.*?:)")
remained a premier programming language for morecre
than a=decade,
and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
mo Web
= cre.search(STR)
the two languages, when used in combination, ideal for
and distributed enterprise
mo.group(1)
application development.

returns
"+?"

':one:'
This tutorial begins with coverage of some of the basics
of Python programming. Using
plenty
of
skill-building
exercises
and
interactive
programming
sessions, this book will
Matches one or more repetitions of the
cre = compile("(o+)")
help
those
new
to
programming
develop
an
understanding
of
concepts
and practical
preceding character, group, or character class.
techniques.
For
experienced
programmers,
the
book
demonstrates
Python's
One of the immediately preceding characters is STR = "Pool" breadth of
capabilities
and shows
that Python
required
to match,
and the
anyways
number
of the interfaces with Java APIs for professional
immediately
preceding characters will match. A mo = cre.search(STR)
application development.
nongreedy multiplier, "*?" will match as few
mo.group(1)
Python Programming
repetitions
as possible.with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important
topics such as:
returns
'oo'
Fundamental programming concepts, including statements, expressions,
cre = compile("(o+?)")
interpreters, and compilers

mo = cre.search(STR)
mo.group(1)
Python basics, including operators, string formatting,
namespaces, classes, errors,
returns
and exceptions
'o'
"??"

concepts
MatchesObject-oriented
zero or one ofprogramming
the preceding
character, cre = compile("(:.?:)")
group, or character class. None of the
mo = cre.search(":::")
File input/output
immediately
preceding characters is required to mo.group(1)
match, and only one of the immediately
Python's intrinsic functions
preceding characters will match. A nongreedy
returns
multiplier, "??" will match as few characters as ':::'
Formatting, parsing, and manipulating strings
possible.
Interfacing with the Java APIs and working with
Java=Streams
cre
compile("(:.??:)")

mo = cre.search(":::")
Using Python and Java Swing to create GUIs mo.group(1)
Working with SQL and JDBC(TM)

returns
'::'

Python and Java applets


In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
E-3. Special
Escaped
and numerousTable
code samples
make this
book a Characters
useful learning experience.
Whether you are a sophisticated computer
user new to programming or a serious
Character Behavior
Example
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

\<No.>

Matches
the same
text matched
STR Class
= "y(aba)d\1"
Python
Programming
with the Java
Libraries: A Tutorial for Building
previously
theEnterprise
group of the
same
cre
= compile(STR)
Webby
and
Applications
with Jython
number.
are numbered 199 mo = cre.search("yabadabadoo")
By Groups
Richard Hightower
and refer to open parentheses
matches yabadaba
counting from
the left.
so mo.group()
Publisher:
Addison Wesley

returns
'yabadaba'
ISBN: 0-201-61616-5
Table of
mo.group(1)
Pages: 640
Contents
returns
'aba'
Characterized by ease of use, richness
of expression, and concise syntax, Python has
remained
a premier
programming
more than a[a-z])"
decade, and is used by
Matches
at the start
of the
string and islanguage
STR =for"(\Athe
equal to
the ^ and
meta-character.
novices
professionals alike. In particular,
its
close
relationship
cre = compile(STR) to Java(TM) makes
the two languages, when used in combination,
ideal for Web and distributed
mo = cre.search("the
beg enterprise
the end")
application development.
mo.group()
returns
This tutorial begins with coverage of'the
some ofb'
the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
Matches at the end of the string and is STR = "([a-z][a-z][a-z]\Z)"
help
new to programming develop an understanding of concepts and practical
equal to
thethose
$ meta-character.
cre = compile(STR)
techniques. For experienced programmers, the book demonstrates Python's breadth of
mo = cre.search("the beg the end")
capabilities and shows the ways that Python interfaces with Java APIs for professional
mo.group()
application development.
returns
'end'
Python Programming with the Java(TM)
Class Libraries: A Tutorial for Building Web
Matches
empty string
at the with Jython
STRcovers
= r'(\be[
a-z][
andanEnterprise
Applications
important topics
sucha-z])'
as:
beginning or ending of a word (that is, cre = compile(STR)
a sequence of characters terminated mo = cre.search("the beg the end")
Fundamental
programming concepts,
including statements, expressions,
by whitespace
or any nonmo.group()
alphanumericinterpreters,
character).and compilers returns
'end
Python basics, including operators, string formatting, namespaces, classes, errors,
Matches an empty
string as long as it's not STR = r'(\Be[ a-z][ a-z])'
and exceptions
at the beginning or ending of a word (that cre = compile(STR)
mo
= cre.search("the beg the end")
is, a position within
a word butprogramming
not
Object-oriented
concepts
mo.group()
between the first or last character and a
returns
space, period,File
etc).input/output
'e b'
(Note: \B andPython's
\b are anchors.
do
intrinsic They
functions
not match any literal characters, but match STR = r'(\Be\B[ a-z][ a-z])'
positions withFormatting,
a string.) parsing, and manipulating
cre = strings
compile(STR)
mo = cre.search("the beg the end")
Interfacing with the Java APIs and working with Java Streams
mo.group()
Using Python and Java Swingreturns
to create GUIs
'eg '
and JDBC(TM)
Matches anyWorking
decimalwith
digitSQL
character.
STR = r'(\B\d[a-z])'
This is equal to [09].
cre = compile(STR)
Python and Java applets
mo = cre.search("3c59x")
mo.group()
In addition, the book contains instructions for downloading and installing the Python
returns
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
'9x'
and numerous code samples make this book a useful learning experience.
Matches any nondigit character. This STR = r'(\d\D\d)'
is equal
to [^09]
. a sophisticated computer
cre user
= compile(STR)
Whether
you are
new to programming or a serious
mo
=
application developer, Python Programmingcre.search("3c59x")
with the Java(TM) Class Libraries will
mo.group()
give you insight into the power of Python
and the know-how to put it to work.
returns
'3c5'
Pub Date: June 28, 2002

\A

\Z

\b

\B

\d

\D

777

\s

Matches
any whitespace
character.
STR Class
= r'(\D\sat)'
Python
Programming
with the Java
Libraries: A Tutorial for Building
This is Web
equaland
to [^\t\n\r\f\v]
= compile(STR)
Enterprise Applications cre
with Jython

mo = cre.search("look at that")
mo.group()
returns
Publisher: Addison Wesley
'k at'
Pub Date: June 28, 2002
0-201-61616-5
\S
Matches any ISBN:
non-whitespace
STR = r'(\D\Sat)'
Table of

character. This
is equal
cre = compile(STR)
Pages:
640 to [^
Contents
\t\n\r\f\v]
mo = cre.search("look at that")
Characterized by ease of use, richness
of expression, and concise syntax, Python has
mo.group()
remained a premier programming language
for more than a decade, and is used by
returns
novices and professionals alike. In particular,
'that'its close relationship to Java(TM) makes
the
two
languages,
when
used
in
combination,
ideal for Web and distributed enterprise
\w
[a-zA-Z0-9_]
STR = r'(\D\D\w\b)'
application development.
cre = compile(STR)
mo = cre.search("No. Calif")
This tutorial begins with coverage of some of the basics of Python programming. Using
mo.group()
plenty of skill-building exercises and interactive programming sessions, this book will
returns
help those new to programming develop an understanding of concepts and practical
'lif'
techniques. For experienced programmers, the book demonstrates Python's breadth of
\W
[^a-zA-Z0-9_]
r'\D\D\W'
capabilities and shows the ways thatSTR
Python=interfaces
with Java APIs for professional
cre
=
compile(STR)
application development.
cre.search("No. Calif")
mo =
cre.search("No.
Calif")
Python Programming with the Java(TM)
Class
Libraries: A Tutorial for
Building Web
mo.group()
and Enterprise Applications with Jython
covers important topics such as:
returns
'No.'
By Richard Hightower

Fundamental programming concepts, including statements, expressions,


interpreters, and compilers

Sequences of Characters

Python basics, including operators, string formatting, namespaces, classes, errors,


The...|... sequence is and
usedexceptions
for alternation and means "or." Its purpose is delimiting multiple
subexpressions. The main expression matches if any of the subexpressions match. The | metacharacter has the
Object-oriented programming concepts
form
File input/output
<expression (<subexpression>|<subexpression>)>
<expression>|<expression>
Python's intrinsic functions
The following expressions both return a match object:
Formatting, parsing, and manipulating strings

>>> search("cat|dog","cat")
Interfacing
the Java APIshave
and working
with
Java Streams
>>> search("a pet(
cat| with
dog)*","I
a pet
dog")
Using Python and Java Swing to create GUIs
This expression also matches:
Working
withdog)*","I
SQL and JDBC(TM)
>>> search("a pet(
cat|
have a pet")
Python
and Java applets
This expression returns dog
:
In addition,pet(
the book
contains
instructions for
downloading
installing the Python
>>> mo = search("a
cat|
dog)*","I
have
a petand
dog")
language
and
the
Java
Development
Kit
(JDK).
Terminology,
definitions,
explanations,
>>> mo.group(1)
and numerous code samples make this book a useful learning experience.
This expression returns a pet dog:
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
>>> mo.group()
give you insight into the power of Python and the know-how to put it to work.
The(...) sequence has the form

777

<expression (<subexpression>)>

It returns a group if the


subexpression
with the
parentheses
matches.
Any text matched
by the
will be
Python
Programming
with
the Java
Class Libraries:
A Tutorial
forgroup
Building
available through theWeb
resulting
match object's
group()with
and groups()
methods.
and Enterprise
Applications
Jython
By Richard Hightower

>>> STR = r'(t\w\w\w) and (t\w\w\w)'


>>> cre = compile(STR)
Publisher: Addison Wesley
Pub Date: June 28, 2002

>>> mo = cre.search("this and that")


ISBN: 0-201-61616-5
>>> Table
mo.group(1)
of
Pages: 640

Contents

returns

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
'this'
novices and professionals alike. In particular, its close relationship to Java(TM) makes
>>> mo.group(2)
the two languages, when used in combination, ideal for Web and distributed enterprise
application development.
returns
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
>>> mo.groups()
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
returns
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.

'that'

('this', 'that')

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
The(?iLmsx) sequence
is used asApplications
a way to include
flags ascovers
part ofimportant
a regulartopics
expression.
It has the form
and Enterprise
with Jython
such as:

<expression (?iLmsx)>
Fundamental programming concepts, including statements, expressions,
This sequence is useful if you
need to use
match() or search() function but have to pass flags with
interpreters,
andthe
compilers
the expression (instead of passing a flag argument to the compile() function and then using its search()
ormatch() methods). The
flags basics,
can be including
one or more
of the set
i ,L ,m
,s, and x. namespaces,
The corresponding
are
Python
operators,
string
formatting,
classes,flags
errors,
I,L,M,S, or X for the entireand
expression.
(Note that, even though the compile object's flags are passed as all
exceptions
uppercase, only the L is passed that way here.) The group containing the sequence itself matches an empty
concepts
string; if it's sent as the onlyObject-oriented
expression, an programming
empty match object
is returned.
input/output
Here's an example in whichFile
a match
object is returned:

>>> search("test(?i)","THIS
IS A TEST")
Python's intrinsic functions
<re.MatchObject instance at 80c87b0>
Formatting, parsing, and manipulating strings
Here no match object is returned because test doesn't match in the string:
Interfacing with the Java APIs and working with Java Streams

>>> search("test(?i)","THIS IS TEXT")


Using Python and Java Swing to create GUIs
>>>
Working
SQL and JDBC(TM)
This example returns an empty
matchwith
object:
Python and Java
>>> search("(?i)","THIS
IS applets
TEST")
<re.MatchObject instance at 80ac768>

In addition, the book contains instructions for downloading and installing the Python
language
andform
the Java Development Kit (JDK). Terminology, definitions, explanations,
The(?:...) sequence
has the
and numerous code samples make this book a useful learning experience.

<expression (?:<subexpression>)>
Whether you are a sophisticated computer user new to programming or a serious
application
Pythonlike
Programming
with the Java(TM)
Libraries
It treats the subexpression
withindeveloper,
the parentheses
a regular expression
but doesn'tClass
return
a group will
if matched.
you insight
into the power
of the
Python
andobject
the know-how
Any text matched bygive
the group
is unavailable
through
match
returned. to put it to work.

>>> STR = r'(~\w+~)(?:\w+)(~\w+~)'


>>> cre = compile(STR)

777

>>> mo = cre.search("~one~two~three~")
Python Programming with the Java Class Libraries: A Tutorial for Building
>>> mo.group(1)
Web and Enterprise Applications with Jython
By Richard Hightower

returns
Publisher: Addison Wesley

'~one~'

Pub Date: June 28, 2002

>>> Table
mo.group(2)
of

Contents

ISBN: 0-201-61616-5
Pages: 640

returns

Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
The(?P<name>...)
sequence
has the
form
the two
languages,
when
used in combination, ideal for Web and distributed enterprise
application development.

'~three~'

<expression (?P<group name> subexpression)>

This tutorial begins with coverage of some of the basics of Python programming. Using
It matches the subexpression
the parentheses,
the matched
text as a group,
justthis
as inbook
regular
plenty of within
skill-building
exercises saving
and interactive
programming
sessions,
will
parentheses, but it allows
the
group
to
be
given
a
name
that
can
be
referenced
later.
help those new to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
>>> mo = search(r'(?P<first>t)(?P<last>est)',"test")
This expression:

>>> mo.group()
returns

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and Enterprise Applications with Jython covers important topics such as:

'test'

Fundamental programming concepts, including statements, expressions,


interpreters, and compilers

This one:

Python basics, including operators, string formatting, namespaces, classes, errors,


>>> mo.group("first")
and exceptions
returns

Object-oriented programming concepts

't'
File input/output
This one:

Python's intrinsic functions

>>> mo.group("last")
Formatting, parsing, and manipulating strings
returns

Interfacing with the Java APIs and working with Java Streams

'est'
Using Python and Java Swing to create GUIs
This one:

Working with SQL and JDBC(TM)

>>> mo.group(2)
Python and Java applets
returns

In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
The(?P=Name...) sequence has the form
Whether you are a sophisticated computer user new to programming or a serious
<expression (?P=name)>
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.
It matches the text matched by the named group referenced earlier in the sub expression.

'est'

This example:

777

>>> cre = compile(r'\w(?P<first>aba)\w(?P=first)doo')

>>> mo = cre.search("yabadabadoo")
Python Programming with the Java Class Libraries: A Tutorial for Building
>>> mo.group(1)
Web and Enterprise Applications with Jython
By Richard Hightower

returns this proper match:


Publisher: Addison Wesley

'aba'

Pub Date: June 28, 2002


ISBN: 0-201-61616-5

This one:
Table

of
Contents

Pages: 640

>>> mo.group(2)
Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
novices and professionals alike. In particular, its close relationship to Java(TM) makes
Traceback (innermost
last):
the two languages,
when used in combination, ideal for Web and distributed enterprise
File "<console>",
line
1, in ?
application development.
returns an error:

IndexError: group 2 is undefined


>>> mo.group()
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
because there's actually
one
group:
helponly
those
new
to programming develop an understanding of concepts and practical
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application
The(?#...) sequence
has thedevelopment.
form

'yabadabadoo'

Pythoncomment
Programming
with the Java(TM) Class Libraries: A Tutorial for Building Web
<expression (?#
text)>
and Enterprise Applications with Jython covers important topics such as:
It allows comments to be inserted in an expression with use of the VERBOSE flag. The contents of the group
are ignored.
Fundamental programming concepts, including statements, expressions,
interpreters, and compilers
>>> cre = compile(r'(yaba)(?#silly
example)(daba)doo')

>>> mo = cre.search("yabadabadoo")

Python basics, including operators, string formatting, namespaces, classes, errors,


and exceptions

>>> mo.group(1)
returns
Object-oriented programming concepts
'yaba'
File input/output

>>> mo.group(2)
returns
Python's intrinsic functions
'daba'
Formatting, parsing, and manipulating strings
The(?=...) sequence has the form
Interfacing with the Java APIs and working with Java Streams

<expression (?=<subexpression>)>
Using Python and Java Swing to create GUIs
It acts as a conditional lookahead and matches expression only if it's followed by subexpression.
Working with
SQL
and JDBC(TM)
Any text matched by the (?=...)
group
is unsaved
and so is unaccessible via methods such as group()
andgroups() .
Python and Java applets
This example doesn't return a match object:
In addition, the book contains instructions for downloading and installing the Python
language and the Java Development
Kit (JDK). Terminology, definitions, explanations,
>>> cre = compile(r'Jython
(?=1\.1)')
and
numerous
code
samples
make
this
>>> cre.search("Jython is stable") book a useful learning experience.
Whether you are a sophisticated computer user new to programming or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
>>> cre.search("Jython
1.1
stable")
give you insight into
theis
power
of Python and the know-how to put it to work.
This one does:

org.python.modules.MatchObject@80ce02a

777

>>> mo = cre.search("Jython 1.1 is stable")

>>> mo.group()
Python Programming with the Java Class Libraries: A Tutorial for Building
and returns

'Jython '

Web and Enterprise Applications with Jython


By Richard Hightower
Publisher: Addison Wesley

The (?!) sequence hasPub


theDate:
form June 28, 2002
Table of

ISBN: 0-201-61616-5

<expression
(?!<subexpression>)>
Pages: 640
Contents

It's a negative conditional


lookahead
of (?=...)
) and matches
expression
only has
if not
Characterized
by(the
easeopposite
of use, richness
of expression,
and concise
syntax, Python
followed by subexpression
. Any text
matched bylanguage
its groupfor
isn't
saved
so isn't and
accessible
remained a premier
programming
more
thanand
a decade,
is usedby
bymethods
such as group() and
groups()
.
novices
and professionals
alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
This example:
application development.

>>> cre = compile(r'Jython


This tutorial begins with(?!1\.1)')
coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will

>>> cre.search("Jython
stable")
help those new tois
programming
develop an understanding of concepts and practical

techniques. For experienced programmers, the book demonstrates Python's breadth of


returns a match object. This one:
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
org.python.modules.MatchObject@80cdb0d

>>> cre.search("Jython 1.1 is stable")

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web
and
Enterprise Applications with Jython covers important topics such as:
doesn't return a match
object:

>>> mo = cre.search("Jython is stable")


Fundamental programming concepts, including statements, expressions,
>>> mo.group()
interpreters, and compilers

Instead, it returns

'Jython '

Python basics, including operators, string formatting, namespaces, classes, errors,


and exceptions

Object-oriented
The{min,max} sequence
has the form programming concepts
File input/output>
<expression {<min>,<max>}
Python's
intrinsic
functions of max repetitions of the immediately preceding
It requires a minimum of min
and allows
a maximum
character, group, or character class. A greedy multiplier, it matches as many repetitions as possible.
Formatting, parsing, and manipulating strings
This example doesn't return a match object:
Interfacing with the Java APIs and working with Java Streams

>>> cre = compile("\$\d{2,3}(,\d\d\d){2,5}")


Using Python and Java Swing to create GUIs
>>> cre.search("salary: $9,000.00")
Nor does this one:

Working with SQL and JDBC(TM)


Python and Java applets

>>> cre.search("salary: $90,000.00")


In addition, the book contains instructions for downloading and installing the Python
This one does return a match object:
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.
org.python.modules.MatchObject@80ce140
youhas
arethe
a sophisticated
computer user new to programming or a serious
The{min,max} Whether
? sequence
form
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the
<expression {<min>,<max>}
?>power of Python and the know-how to put it to work.
It's the same as {min,max}, but as a nongreedy multiplier, it matches as few repetitions as possible. Thus,

777

>>> cre = compile("(:.{3,10} :)")

Python Programming with the Java Class Libraries: A Tutorial for Building
>>> STR = ":one:a:two:"
Web and Enterprise Applications with Jython
By Richard Hightower
cre.search(STR)

>>> mo =
>>> mo.group(1)

Publisher: Addison Wesley

returns

Pub Date: June 28, 2002

Table of
':one:a:two:'

Contents

ISBN: 0-201-61616-5
Pages: 640

>>> cre = compile("(:.{3,10}


?:)")
Characterized by ease of use,
richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by

>>> STR = ":one:a:two:"


novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise

>>> mo = cre.search(STR)
application development.
>>> mo.group(1)

This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming sessions, this book will
help those new to programming develop an understanding of concepts and practical
':one:'
techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application
development.
The[...] sequence
has the form
returns

Python Programming
with the Java(TM) Class Libraries: A Tutorial for Building Web
<expression [character
class]>
and Enterprise Applications with Jython covers important topics such as:
It matches any one of the characters within the brackets, listed explicitly or as a range delimited by the
(hyphen) metacharacter (it understands [12345] and [1-5] as the same). Popular ranges are [0-9], [a-z], and [AFundamental programming concepts, including statements, expressions,
Z]. Multiple ranges, such as [a-zA-Z], can also be used.
interpreters, and compilers
The following examples all return a match object:
Python basics, including operators, string formatting, namespaces, classes, errors,
and exceptions
>>> search(r'[RTL]oad',"Toad")

>>>
>>>
>>>
>>>
>>>

search(r'[RTL]oad',"Road")
Object-oriented programming concepts
search(r'[RTL]oad',"Load")
search(r'199[7-9a-z]',"1998")
File input/output
search(r'199[7-9a-z]',"1999")
search(r'199[7-9a-z]',"199x")
Python's intrinsic functions

The[^...] sequence hasFormatting,


the form parsing, and manipulating strings

<expression [^character
class]>
Interfacing with
the Java APIs and working with Java Streams
The opposite of [...], itUsing
matches
anything
but the
characters
listed
within the brackets. Possible characters
Python
and Java
Swing
to create
GUIs
can be listed explicitly or as a (hyphen) delimited range.
Working with SQL and JDBC(TM)
This example returns a match object:
Python and Java applets

>>> search(r'199[^1-7]',"1998")
This one doesn't:

In addition, the book contains instructions for downloading and installing the Python
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.

>>> search(r'199[^1-7]',"1997")

Putting

Whether you are a sophisticated computer user new to programming or a serious


application
developer, Python Programming with the Java(TM) Class Libraries will
Things
Together
give you insight into the power of Python and the know-how to put it to work.

A third-party vendor I (Rick Hightower) worked with once had a problem reading the IDL files we were trying
to integrate with its product. Specifically it didn't like identifiers beginning with ::, as in
::com::mycompany::Employee, preferring com::mycompany::Employee. My job was to

777

convert the IDL filesPython


to their Programming
liking, which I did
using
The code
I wrotefor
to Building
do this is just
with
the regular
Java expressions.
Class Libraries:
A Tutorial
four lines long (actually
butEnterprise
four with a Applications
little cheating).with Jython
Websix
and
By Richard Hightower

Here's the code to read in the file and write all the replacement text:
Publisher: Addison Wesley

f=open(filename)
Pub Date: June 28, 2002
fstr=re.compile(r'\s((::)(\w+))\b').sub(r'
\3', f.read())
ISBN: 0-201-61616-5
f.close();
f=open(filename,
"w")
Table of

Pages: 640
f.write(fstr);
f.close()
Contents
Characterizedfunction:
by ease of use, richness of expression, and concise syntax, Python has
Here's the complete fixIDL()
remained a premier programming language for more than a decade, and is used by
import re
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
def fixIDL(filename):
application development.

f=open(filename)
This tutorial begins with coverage of some of the basics of \3',
Python programming.
fstr=re.compile(r'\s((::)(\w+))\b').sub(r'
f.read())Using
plenty
of
skill-building
exercises
and
interactive
programming
sessions,
this book will
f.close(); f=open(filename, "w")
help
those
new
to
programming
develop
an
understanding
of
concepts
and
practical
f.write(fstr); f.close()
techniques. For experienced programmers, the book demonstrates Python's breadth of
The key is the regular
expressionand
r'\s((::)(\w+))\b'
breakwith
it down
itsfor
most
basic
capabilities
shows the ways that Python. Let's
interfaces
Javainto
APIs
professional
application development.
components:
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web

\s whitespace
and Enterprise Applications with Jython covers important topics such as:
\w alphanumeric
Fundamental programming concepts, including statements, expressions,

\b word boundary
interpreters, and compilers
+ one or more

Python basics, including operators, string formatting, namespaces, classes, errors,


and exceptions
Now let's see how these components are used:
Object-oriented programming concepts

(::)(\w+) find
a sequence
of characters that begins with ::, followed by one or more
File
input/output

alphanumeric characters
Python's intrinsic functions
\s(()(\w+)) find a sequence of characters that begins with whitespace, followed by ::, followed
by one or more alphanumeric
characters
Formatting,
parsing, and manipulating strings

\s((::)(\w+))\b
findwith
a sequence
characters
that begins
Interfacing
the JavaofAPIs
and working
withwith
Javawhitespace,
Streams followed by ::,
followed by one or more alphanumeric characters, followed by a word boundary
Using Python and Java Swing to create GUIs

Working with SQL and JDBC(TM)

re.compile

Python and Java applets

There.compile call compiles the regular expression. It returns a regex object that has a
In addition, the book contains instructions for downloading and installing the Python
sub() (substitute)
method. The call to regex.sub(r'\3\,f.read()) means replace
language and the Java Development Kit (JDK). Terminology, definitions, explanations,
the matched text
with
a space
andsamples
the thirdmake
group.
and numerous
code
this book a useful learning experience.
A group is defined by
the parentheses
regex andcomputer
read fromuser
left new
to right.
Thus,
Whether
you are ainsophisticated
to programming
or a serious
application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.
((::)(\w+)) defines group 1

777

(::) defines group 2

(\w+) defines group 3

Python Programming with the Java Class Libraries: A Tutorial for Building
Group 0 is always the
whole matched regex. Group 3 is important because it represents the text without the
Web and Enterprise Applications with Jython
preceding::.
By Richard Hightower

Now we'll break down the code line by line, each line followed by its explanation.
Publisher: Addison Wesley

import re

Pub Date: June 28, 2002


ISBN: 0-201-61616-5

Table of
imports
the re (regular expression)
module.

Pages: 640
Contents

def fixIDL(filename):
Characterized by ease of use, richness of expression, and concise syntax, Python has
remained a premier programming language for more than a decade, and is used by
defines the fixIDL() function with an argument of filename .
novices and professionals alike. In particular, its close relationship to Java(TM) makes
the two languages, when used in combination, ideal for Web and distributed enterprise
f=open(filename)
application development.
opens a file corresponding to filename .
This tutorial begins with coverage of some of the basics of Python programming. Using
plenty of skill-building exercises and interactive programming
sessions, this book will
fstr=re.compile(r'\s((::)(\w+))\b').sub(r'
\3', f.read())
help those new to programming develop an understanding of concepts and practical
does the following: techniques. For experienced programmers, the book demonstrates Python's breadth of
capabilities and shows the ways that Python interfaces with Java APIs for professional
application development.
re.compile(r'\s((::)(\w+))\b') compiles the regular expression into a regex object
Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web

.sub(r' \3',
f.read()) replaces every occurrence of the matched text with the third group
and Enterprise Applications with Jython covers important topics such as:
in the match, returning a string with the text replaced

f.read()) reads
the entire file
into a string:
Fundamental
programming
concepts, including statements, expressions,
interpreters, and compilers

f.close(); f=open(filename, "w")

Python basics, including operators, string formatting, namespaces, classes, errors,


then closes the file ( f.close()) and reopens it in write mode:
and exceptions

f.write(fstr); f.close()
Object-oriented programming concepts
It then writes the entire newFile
textinput/output
into the file and closes the file.
Here's another way to writePython's
the code:
intrinsic functions

f=open(filename) Formatting, parsing, and manipulating strings


fstr=re.compile(r'\s((::)(\w+))\b').sub(r'\3',f.read())
f.close();
Interfacing with the Java APIs and working with Java Streams
f=open(filename, "w")
f.write(fstr); Using Python and Java Swing to create GUIs
f.close()
Working with SQL and JDBC(TM)
But then I would have lost my bet that I could write this utility package in four lines.
Python and Java applets
Note
In addition, the book contains instructions for downloading and installing the Python
This appendix language
summaryand
wasthe
written
Rick Hightower.
Java by
Development
Kit (JDK). Terminology, definitions, explanations,
and numerous code samples make this book a useful learning experience.

CONTENTS

Whether you are a sophisticated computer user new to programming or a serious


application developer, Python Programming with the Java(TM) Class Libraries will
give you insight into the power of Python and the know-how to put it to work.

777

Das könnte Ihnen auch gefallen