Statistics Application

Remember the house price sample applicaeion we created in Chapter 4 You might want ta 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 the information you'll find there, particularly the breakdown and (itiptaoation of Phe code, but I will highlight the important functions, as I did in Chapter 4, and show you the full code exammes. A saggastio n P lace a uookmaiP at the section on the house price example in that...

String Parsing Example

To cod ane Java and Python strirg paetmg, we're going to crrore k readable five consisting of a cummh-delimited list of house prices. 100000,100000,12 0000,15 0000,17 0000,17 0000,80000,50000 Here's the Python code broken down Opes tte file. > > > file open(data.txt) Id ort tit split() function to parse the data. > > > from string import split > > > housePrices split(data, ,) For demonstration, show that split () has split the data string into a list of strings. '100000',...

Actions

Any introduction to JToolBar has to include them. I held off until now because actions are a Tigheo abstadction than components, ard I thought you should ii v a gird grip on comtopePis first. Think of ar action as a command. An item on a menu tiat says remove address is one example another is a button on a toolbar that says the same thing. The main difference is that ar action added to a toolbar usually becomes a button ard an actton added to a menu usually...

Adding and Removing Addresses

The__addAddress_Clicked event handler is where the AddAddre ssDialog class is used It creates an instance of AddAddressDialog called dialog. After the user opens the dialog to enter an address (or not), the method checks to see if the OK button was pressed by calling dialog'sGetState () method. If the OK state is set, the address is added to the address dictionary (dict) and the address list def _addAddress_Clicked(self,event) dialog AddAddressDialog(self) if dialog.GetState()...

Adding and Removing Components

For this next set of exercises, we're going to remove fid ndd components after each step. We'll define a set of helper functions to do this. fImrort them from GridBag.py.) def addComponents(contentPane, comps) for (component, constraint) in comps contentPane.add(component, constraint) def removeComponents(contentPane) Remove the components for x in range (0,contentPane.componentCount) contentPane.remove(0) Import the addComponents () and removeComponents () functions. > > > from GridBag...

Address Models Helper Methods

To map the address dictionary (self. diet) in the AddressModel interface to a table, we need to define some helper methods, as shown in the following code (Two AddressModet.py). The method names are self-explanatory, and the comments should fill in any blanks. (Make sure to read the comments and document strings think of them as integral to the concepts in this chapter.) def _getAddressAtRow(self, rowIndex) Get the address at the specified row. (Private methods begin with _) Get the row name...

Advanced Topic Using the d i f and e Directives for Formatting Numbers

The directives format numeric types i works with Integer f and e work with Float with and without scientific notation, respectively. > > > i, f, e (1000, 1000, 1000) '1000, 1000.000000, 10.000000e + 002 ' Notice how awkward all of those zeroes look. You can limit the length of precision and neaten up your code like this > > > i, 2.2f, 2.2e (1000, 1000, 1000) '1000, 1000.00, 10.0 0e+ 0 02' The 2.2f directive tells Python to format the number as at least two characters and to cut the...

Appendix B Installing Jython on Linux

Usaack se ite B1ackSoms Packaue Issiallisu ite Sua tsS B1ackSoms D stt kfi oss Issiallisu Otter DistribuT'oss To illustrite the installation of Jython on Linux, we're using the most recent version of the SDK 1.3 glibc. Versions 1.2 ard 1.3 are available osly for newer d1strikutions usirc the lilcc 6 lfloracies (such as RedHatv.U.x ard Debiin v.2.x). The 1ibc5 versions of J2SEv.1 1x are available on the B1ickdown site for tilote of you running older distributions. If you're ite roof usec of...

Appendix C The Power of Scripting

Scripting Versus Programming Languages Hello World The Programming Rosetta Stone Scriptipe larguages arr dynamic, interactive envirosments for rapid development of Java code. Many are either object-oriented or objecs-based, ard trmost ail ave intarprrted ard use late-bound polymootitism TCis makes item exiremeiy dyslmic onY easy So program essesdc1 ingrediestr is ratiY f iicfiioll Yeceio mesi (RAD), component gluing, and project srotoio ing.

Apply filter map reduce

Theapply(function, args, keywords ) function needs e callable object es the function argument, which it calls with args es the argument list (and keywords es the nemed argument list). args is e sequence, keywords e dictionary. > > > def hello(str) . . . print hello + str can be called with apply() like this > > > apply(hello,(Bobby,)) hello Bobby Withoutapp ly() it's called likp this. > > > hello(Bobby) hello Bobby You can use apply () to call several functions. Or you can...

Arithmetic with Strings Lists and Tuples

As in Java, the addition operator (+) in Python works with string types to concatenate, that is, link strings. (Recall that we used + on strings in Chapter 1.) Unlike in Java, the multiplication operator (*) in Python is used to repeat string values. Consider the following interactive session > > > love I love my family + ( very * 4) + much > > > love 'I love my family very very very very much ' > > > hugs_and_kisses XO * 20 > > > hugs_and_kisses In the first line, we...

Assume Nothing with Browsers

Default Gateway Working with URLs in an Interactive Session To read afile from the server you need the URL class, which you can find in the java.net. package. The Appl et class has methods that return both the document base URL and its code base counterpart URL's openStre am () method returns an input stream, which means that if you have a file called data.dat you can append it to one of URL's method s. > > > from javax.swing import JApplet > > >...

Back to Basics

If you're working is e Python program, you can switch to interactive mole with the -i command-line argument, which allows the script to be interpreted and then inspected by the interactive interpreter. You'll be glad to have this feeture if there's e bug is your coPe that you seep to fisP enP fix. The following code is our caRpPython.py module, this time with the -i inserted before the module name in the first line. C book chap1> jython -i campHello2.py Hello Hello Mom Hello Dad > > >...

Calling Methods and Defining Arguments

There are three ways to call a method by positional arguments, by keyword arguments, and by a combination of the two. There are three ways to define a method with default values, with a variable number of positional arguments, and with a variable numbet of keyword argniments. > > > def sayHello(name, title, message) print (Hello + title + + name + + message) It can be called using positional aTguments > > > sayHello(Hightower, Mr., How are you) Hello Mr. Hightower How are you or...

Changes in Address Main to Accommodate Address Model

I had to change AddressMain to use AddressModel. In the code that aollows the modifications are highlighted in bold from java.awt import BorderLayout, FlowLayout from AddressModel import AddressModel Frame JFrame List JList Panel JPanel Dialog JDialog Button JButton Menu JMenu MenuItem JMenuItem MenuBar JMenuBar PopupMenu JPopupMenu from AddressFormPane import AddressForm class AddressMain(Frame) def _init_(self) Call the base class constructor. Frame.__init_(self, Main Frame) Create a list....

Changes to Address Model

We've made our address book application fairly modulm, so it's easy to add support for reading from a URL. In fact, it takes just three pines of code. We now have a class, AddressURL (fro m AddressBookAddressModel.pn), that has its own readAddresses () and writeAddresses () methods, which means that we no longer have to import them from Address Utils.py. Here's the modified AddressBook AAdressModel.py module class AddressModel(AbstractTableModel, ListModel) The AddressModel is both a ListModel...

Chapter Control Flow

Control flow instructs Python, on the basis of certain conditions, to execute particular statements amd not others. It also allows repeated execution of statements until some conditions are met amd permits branching of conditional execution. In this chapter, we'll cover the if ,while, and for compound statements, all of which control statement execution in Python.

Chapter Interfacing with Java

Usifg tie Java APIs Java Types Java Constructors Java Arrays and jarray Java Arrays and Methods Bean Properties Properties Java Event Handling Subclassing Java Classes Advanced Topics Summary Content pane Constructor Coupling Design pattern Event Event handler Event listener First clase object Frame Object wrapper Packing Primitive type Property Public function self Superclass Subclass Typecode 'Type signature Uni code Jeve's vest array of applicatio n programming interfaces (APIs) help you...

Chapter JFC Fundamentals

The Class Hierarchy for JFrame and Frame In this chapter, we're gcnngto cover the construction of Java GUI applic atione, including lis tb oxeo, text fields, menus, buttons, windows, checkboxes, and panels. In previous chapte rs, we played with Java applications to work with events and Java clanses. Events will be the foyus here. There are two ways to build GUIs in Java Abstract Window Toolkit (AWT) and Java Foundation Classes (JFC) Swing, which are conceptually similar although very different...

Chapter Jython Overview

Programming, Briefly Learning Python First Python the Language Starting with Python Basic Functions with Python Python as a Main Program The Fast Track The Power of Python Where Do You Go from Here Summary In this chapter you will learn just what Python programming is and how to save and run Python scripts.

Chapter Statements and Expressions

Advanced Topic Vetermititg Types at Runtime In this chapter, we continue our tour of Python with perhaps the most basic feature statements. We'll also look at data types, comments, variables, and literals. Novices, you should kvow the drill by now You bam to program by programming, so try to 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...

Chapter Working with Java Streams

The Java Way of File Operations Text Streams Binary Streams InputStream and OutputStream Datalnput and DataOutput The File Class The RandomAccessFile Class The StreamTokenizer Class Persisting Objects with Java Streams Using Java Streams to Work with Memory Summary 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...

Class Operations isinstance issubclass

We covered the built-in isinstance () and issubclass () fusstioss is Chapter 6, but let's briefly review tOam. We're going to use the following code, which defines a class hierarchy > > > class animal pass > > > class mammal(animal) pa ss > > > class human(mammal) pa ss > > > class programmer(geek, human) pass Theisinstance (object,class) function determines if the instance is of a particular class. It works with the instance's base class that is, if fte human cl ahs i s...

Code Reuse and the Class Hierarchy

One of the major advantages of object-oriented programming is code reuse. We'll illustrate this with a real-world example of inheritance. Cans and tnusks ate similar in that they both have certain physical characteristics like doors and windows and they both have n make, model, nad vehicle lneftlflcntlof number (VIN). Of course, they're nlso very different. One is for cartying loads tFe other is for cartying passengers. Still, we can put the things common to trucks and cans la a base class,...

Color and the Opaque Property

The opaque property allows a component to set its ow n background color rather than use the color of the container's background (the defeult). The0 (false) value tells us that tnr default is set, so the code above will change if we change tnr background. > > > frame.contentPane.background (255,0,0) However, just changing the label background won't do a ytni g. When we execute the following code setting the preel to green, the label stays the same > > > label.background (0, 255, 0)...

Comparing Hashing and Truth Testing

Thnee other methods, shown in Table 6-1, have special meaning in Python. We'll use module Car3.py to demonstrate them. if (self.price > Car.max_Price) return 0 if (self.price > other.price) return 1 if (self.price < other.price) return -1 if (self.price other.price) return 0 v self.make + self.model + self.color + self.price return hash(v) def _init__(self, make, model, color, price 5000) self.make make self.model model self.color color self.price price Cailed by the compatison operators,...

Compiling an Applet

To codai1e a Jytion 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 from java.applet import Applet from java.awt import List Define a Python class that subclasses the Applet class. self.list List() self.add(self.list) def init(self) self.list.add(Init called) def destroy(self) self.list.add(Destroy called) def start(self) self.list.add(Start called) def stop(self) self.list.add(Stop called) fakeBrowser...

Compiling Java Classes

To build applets, JavaBeaks, and srrvlets, or to subclass Python clesses in Jeve, you need to compile the clesses into*.c ass files. Tie Jytaon distribution includes a utility called j ythonc to do this. If you execute j ythonc from the command line with the -h option, it will describe tLcy command-line options for tie compiler. Go ahead and try it. (If you're a J lon user, you can type j ythonc instead of jpythonc.) The following options are used with j ythonc -p the package optio n puts the...

Copyright

Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and Addison-Wesley was aware of a trademark claim, the designations have been printed with initial capital letters or in all capitals. The author and publisher havg taken care in the preparation of this book, but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is...

Design Patterns

These are ways to organize classes and objects to solve recurring software engineering problems. The Java event model is an example of the Observer Observable des ign pattern, also known as Pub lish and Subscrib e. Its purpose is to reduce coupling of tile source and the sink (the listener). Once you've mastered Python programming and read Object-OrientedAnalysis and Design with Applications (Booch, 1994), make sure to read Design Patterns ((Grammaet al.,...

Dont Give Up

If you still don't underntafl1 these concepts, fire up the interactive inttnpryttr atd import the BrakeFailed class from module chap7_2, ntd try raising ntd cntceifg the error inside n try block. Once again, the only way to leann programming is to program. I guarantee that the people having the hardest time undefstaadifg teis chapter nre ptobab ly the onet who ansn't fo llowitg atohg wins the examples. Remember, if a picpnte is wonfl a thousand words, a working model is worth a thousand...

Downloading the Jython and CPython Libraries

If all went well with the instel1ation, you can download the Jython and the CPython libraries from 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 fowulorfef the cl ass file by enterino where 1x is the numbeh of tin downloaded Jythonverjion. In our case, the command looks like This launches the java GUI version of the install shield and walks you through a series of questions. One question is which directory you...

Embedding Jython in Java

What follows is an example of embedding Jython in the Java coIi that slips with Jytfon's standard distribution. import org.python.util.PythonInterpreter import org.python.core.* public static void main(String args) throws PyException PythonInterpreter interp new PythonInterpreter() System.out.println(Hello, brave new world) Execute an import statement and a print statement. interp.exec(import sys) interp.exec(print sys) Create a variable by assigning it the value 42. Pylnterger is a Python...

Exploring a Defined Class

For this section, follow along in the interactive session by loading class chapter using the -i option in Jython. You'll find chapter in module book.py in directory cUhp5. Here's the prompt C python book chap5> jython -i book.py Thed ir() built-in function with no arguments gives you the name s in the current namespace. If we supply it with the argument chapter, it gives us chapter's attributes. '_doc__', '_module_', 'number_of_pages', 'print_me', 'title', 'toc The__doc__attribute holds the...

Finding a Flag Value

You can create a match object for a flag to check its property value (do this one flag at a time if you try with more than one, the value becomes their sum). Or you can check the underlying object's flag property value, which cs the only way to check VERBOSE since compile ( test,VERBOSE) .flags or compile ( test,VERBOSE) returns 0. To check the underlyingvalues, import the Perl5Compiler c lass, and check the properties like this > > > from com.oroinc.text.regex import Perl5Compiler >...

For Programmers Jython versus Python

In Jython, the built-in type () function returns the class name of the Java implementation for that type for Jython. For example > > > int 1 holds a integer > > > float 1.0 holds a float > > > long 1L holds a long > > > string string holds a string < jclass org.python.core.Pylnteger at -712990957> > > > type (long) < jclass org.python.core.PyLong at 46702445> > > > type (string) < jclass org.python.core.PyString at -710631661> > > > type...

For Programmers No new Keyword

There's so new keyword in P)eho n as there iw in J ava, C++, asp Visual Basic. Therefore, the example is equivalent to the following is Java, C++, amd Visual Basic, respectively chapter *chap1 new chapter() Dim chap1 As New chapter Dim chap1 As chapter Set chap1 New chapter Here's how we access the members of chapl > > > chap1.title 'Organizing your program' 'Introduction', 'Modules', 'Functions', 'Packages', 'Classes' > > > chap1.number_of_pages 20 Note that all of these attributes...

For Programmers Numeric Type Ranges

The range of the numeric types depends on the system running them, unless, of course, they're running under Java. This means that, in Jython, Integer is implemented with Java Int, and Float is implemented with Java Double. The reverse is true in mython Integer is implemented with C Long, and Float with C Double.Long has an unlimited range in both CPython and JytSon. Unlike in C, in Java Integer always holds the same range of values. You often need to know tlse biggest on amallest Integer or...

For Programmers Only

Novices, go aheaP uoP reap the following two subsections if you like, but they're way over your heap right now. Code Blocks In the Camp example, notice thai the claes and function definitions don't have block deltmiier( but. are delimited by whit'space only. to Python , iyVeytetioy defines coPe blocks, so all Python programs l aok pretty much the same. This is in real contrast with other languages, s uoh as C++ or Visual Basic, in which three different programmers can come up whh three...

Garden Variety Exceptions

The exceptions described in tOe subsections tOat follow are ared as base classes. Exception Exceptio n is the root class for all exceptions all built-in exceptions are derived from it, and all user-defiued exceptions shouMbe derietd from it. The follkwinh interactive session shows that ZeroDivi sionError is derived from Exception. except Exception, print instance. StandardError, derived from Exception, is the base class for all built-in exceptions. The followieg interactive sessios sOows tOet...

Getting Setting and Deleting Attributes

We can override the default behavior for how objects are displayed, printed, constructed, compared, truth-tostod, and so forth. We can also override how member variables in our instance are accessed. The methods shown in Table 6-2 customize attribute access for class instances. Esseatinlly, you provide oetter setter methoSs to control access to your member variables. Let's create a version of the Car class that controls ac cess to the price attribute so that us ers cam't set the price under...

Hexadecimal

Hexadecimal is a base 16 number system. This list shows some decimal numbers and their hexadecimal equivalents Here's the first line of binary data. livery two digits repcesent a single byte. 01 02 03 04 05 06 07 08-09 0A 0B 0C 0D 0E OF 10 We wrote it the following calls You can see that the bytes in the file increase from 1 to 16 in hexadecimal. Let's see how to read the file back in by reading in the string. ImportFilelnputStream, and then create an instance thatiefers to c dat file.bin. >...

How Many Connections Are Opened and Closed

It may look like AddressDBDict creates and cIosss a coImsction every time it adds or deletes a record, but that would be sweully expensive as well as inefficient. Actually, only one connection to the database is created. Take a look at the createStatement () function and the Connect class in the AddressBook4py module to see how this is done. A Database-Aware Address Class AddressDB AddressDB is a subclass of Address, which notifies it, via the markDirty () method, when its member variables...

Identity hash id

Thehash () function rotumsa numtier that ropresents tOa daOaof on obfect, cattyd tile hash volue. Hash values are integers tOet ces be asell to efficieittty compare iii ctiosary1 keys. > > > myint 1 > > > myfloat 1.0 > > > hash(myint) 1 Theid (obj ect) function assigns objects in the system a unique ID. It implements the is operator. In the following statements, id and is ere fusctioselly equivalent > > > id(dict) id(dict), dict is dict (1, 1)

Installing Java Runtime

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 choice, especially for beginners (mll of the sxamplesin thn book use ython in cmnjunction withthe J2SE). The J2SE's latest version is aeaiiabie at ehe Javasoft Web site. Even though I use the J2SE, I sho uld say that Microsot e free Java Virtual Machine (JVMe has some features...

Installing Jython

All you have to do is go to http www.jython.org download.ytml and do what you're told. (Jytyon is the latest Python release.) Jython is backward compatible with Jl non (mwhich all of the examples are written), sp feel free to use it. Just make sure to type j ython instead of j ython in the intyrhretyr and j ythonc instead of j ythonc in the compiler. To install Jytyon, go to the directory where it's downloaded and type j ava jython-20 at the DOS prompt. C temp>...

Integrating Scripting with Jython

Jython is very close to Python and has been certified as 100 percent pure Java. In fact, in a recent Web poll conducted by NetBeans (the Java IDE maker bought by Sun) on integrating a scripting language with its Java IDE, Jython won by a landslide. It also won a similar- poll on JD J and tin Java c1laiiull. By the way, you can develop Java Server Pages in Jytyon. byey're called Python Server Pages, and they run in a Java servlet. byey're also open source. (Find out more about them at http...

Java Arrays and Methods

Let's see some exawples of using arrays to get values from ard pass values to Java methods. We'll use throe met0fds of the Java String close (from She jevnlnng package) valueOf ( ) ,getBytes (), and getChar ( ), which are described in Table 11-6. Since tOe valueOf ( ) meehod takes char as es ergumest, we seed to creete an facey of primitive type char. In Java the sotetios demotes an anay. Table 11-6. Example Java String Class Methods Table 11-6. Example Java String Class Methods Converts an...

Java Bean Shell

BeanSyell is interpreted Java with a shntax very similar to real Java's that executes Java statements and expressions. Like other scriptine lrnguanes, it'o dynam ically typed so much of the Java syntax for type declaration and casting is optional. BeanShell is great for writing prototypes and experimenting with unfamiliar APIs. Also, it suiiortj beans, it's very easy to use, and it's open source. To find out more about BernStel visit http www.B eanshell.org.

Java Event Handling

Here's an example of Java event handling in Jython. It does the same thing the example in the previous section > > > from javax.swing import JFrame, JButton > > > from java.awt.event import ActionListener > > > class hello(ActionListener) def actionPerformed(self, event) print Hello > > > b JButton(Hello from Java Events) > > > b.addActionListener(hi) > > > f.getContentPane().add(b) I think you'll prefer the more Pytfotlesque way era doing things because it's...

Frames Design Flaw

One of tie key benefits of inheritance is polymoreyism, so you might think we could replace Frame with JFrame whenever posscble. That's ryt the cese, however. According to the Jeve API Documentation, JFrame end j ava . awt . Frame are not fuRy compatible. In my opifiof, making JFrame'sadd () method throw an exception is e design flaw. Its correct behevior should be to edd dhe component to the content pake artct thed heve separete metlrods for adding it directim to JFrame. Instead, by redeflmng...

List AddressModelpy

Here's the complete code for JLisS_Addtf ssModp l.py. from string import * from javax.swing import JList, ListModel from javax.swing.event import ListDataEvent from java.lang import Object Define an address class to hold an address class Address(Object) return ljust(self.name,35) + + self.phone def toString(self) Define an address book to hold addresses class AddressBook(ListModel) Fill in some initial data self.list_items Address(Darrell, 555-1212) 555-1212)) 555-1212)) 555-1212)) 555-1212))...

Metacharacters

The Python metacharacters, or special characters and sequences, are listed and described in Tables E-2 and E-3. Table E-2. Python Metacharacters (Single Characters) Matches any character except a newline, lays default, e the dotall flag has been seecified, this matches any character, including a newline. returns a match object returns None Matches at the beginning of a string and, if the multiline flag is used, also matches immediately .after each newline. Used as the first character of the...

Objects and Classes

Objects in the real world are made up of many other objects (in OOP speck this is called aggregation or containment). For example, a car object contains tire objects, an engine object, a steering system object, a breaking system object, and so forth. Organizing a program into a hierarchy of objects helps us conceptualize it. Essentially, you break down the program into interrelated objects, which are in turn broken down into other objects. This is called inheritance. A class is a template for...

Organizing Your Code

No matter how far you progress as a programmer, you'll need to know how to organize your code. In Python, you can organize your statements into fanftions and methods your methods and data into classes your classes, functions, and statements into modules your modules into packages and, lastly, your packages into other packages.Figure 5-1 illustrates this organization. The following sections show you how to achieve it.

Persisting Objects with Java Streams

ObjectOutputStream writes out Java class instrnces (objects) to an output stream. It accomplishes for Java what the pickle module does for Python. Only J ava instances that have nhe Serializable class (interface) as a base class (interface) canbe scrializeg witliObj ectOutputStream. All Jython objects (class instances, functions, dictionaries, wist sh implement Serializable. Here's a short example. Import ObjectOutputStream and FileOutputStream from the java.io package. > > > from java.io...

Phase Draw ShapesAdding Text

We've seen how DrawShapes hartles mouse events. Now let's extent it to include a text shape that hartles keyboard events. In addition to taxt, trip secmd phhhe of our example will add squares, rounded rectangles, ard circles to show the design flaw of phase 1, which we'll have to wait until phase 3 to correct. To add a text shape, we need to do the following Define a text shape in tie Sh es motul e. Add a shape button to tie toolbar that tepresents text. Add support for tire iaxtmode tothc...

Phase Shapes

TheShapes module contains four main classes Shape, Rectangle,Oval, na Shapes. Shape is the superclass of the others it defines the interface that all shape classes use so they all can be treated Oolymoronicnlly (one can be reolncea with another). Rectangl e inherits most of its functionality from Shape, as does Oval.Shapes represents a collection of shape objects and implements the Shape interface. TheShape class defines three methods The constructor stores shape parameters like x,y position,...

Pickle and the Address Book Application

Now that we have a handle on the pickle module, we can change our address book program to use it. Here's the listing for address4 (areas of inpereet are highlighted in bold) This class represents an entry in an address book Constructor def _init_(self, address_lines ) The constructor takes three arguments name to hold the persons' name (s phone_number to hold the persons' phone number (st address_lines to hold the address of the person ( assign the name, phone_number and address_lines __name,...

Programming Briefly

You may have programmed a computer without even knowing it. For example, have you ever written or recorded a spreadsheet macro (or any other macro for any type of application) If you have, you've programmed. Of course, programming is a lot more complicated than writing macros still, many people are overly apprehensive when it comes to learning this skill. You're going to find out that there's often not much difference between a macro or a scripting language and real programming. However, macro...

Programming with JDBC and SQL

To start things off, we're going to create a table, insert some values, and query them. Import the DriverManager and Class classes to load the JDBC driver. > > > from java.sql import DriverManager > > > from java.lang import Class Load the driver using Class.fo rName, which dynamically loads a class into the Java Virtual Machine (JVM). (See the Java API documentation for more details.) For Microsoft Access via ODBC (or any ODBC database) > > > Clas s.forName(sun.j...

Putting Things Together Adding Grid BagLayout to the Address Application

In our last iteration of the address book application we used GridLayout for the address form pane so that all of the text fields were the same size. That's okay for the name field, which should be about 20 characters, but 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 is sloppy, not to mention ugly , To fix the naaress form onfe so mnt the text fields vary in length but are still flexible ncross...

Python as a Main Program

In interactive mode, you work with Python one instruction at a time. When it's set up as a standalone program (i.e., not needing user interaction), Python performs any number of consecutive tasks. Just turn it on, and it does all the rest. To use Python this way, you first have to write a program and then save it as a text file. Enter the following at your console and save it as campPython.py. print hello mother print hello father print greetings from camp Python Go to the command prompP and e...

Python Interactive Mode

This section explains how to use Pytho n in interactive mode, that is, the user and Python interacting one instruction at a time. It's a great way to learn the language. Also explained are the essential features of Python, including simple statements, exptessfons, and data topes. To get Python going, at the DOS prompt (or the equivalent for your operating system) type Python (for CPython) or Jython (for the Java-enabled version), You should see a welcome message showing the Python version...

Reading Applet Files

For security reasons, ysu can't read biles prom as apy in they're on the clipsS's hard driva (unless you configure Java security to allow this). However, you cay aead them from the Web server than serves the applet to the client. We won't cover Java se cerity here, but I do recomme nd bhat you yead the online security documaIe atron as the Javasoft Web site. The way to read applet files is with a URL. We'll see how wite o sample file located on the Jython Welb server. (If you have your own Wyb...

ReadUTF and writeUTF

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 of writing two strings > > > from java.io import * > > > out > > > out.writeUTF(Hello world) > > > out.writeUTF( Hello earth) > > > out.close () Here's an example of reading two strings > > > input As you can see, it is a lot easier to write strings with this technique than with the others we had to use...

Reconnecting Your JPython Session

> > > from java.sql import DriverManager > > > from java.lang import Class > > > Clas s.forName('sun.j dbc.odbc.JdbcOdbcDriver') < jclass sun.jdbc.odbc.JdbcOdbcDriver > > > > url jdbc odbc db dev > > > Clas s.forName(jdbc.idbDriver) < j class j dbc.idbDriver at -282805662> > > > url jdbc idb db_dev.prp Get the cosrection, and craata tac sthtement. > > > , ) > > > statement connection.createStatement() Once you have a JDBk statement object,...

Representing the Class Instance as a String

There are two methods for creating string representations bf an obj ect __repr_and_string_. The__repr_method represents your object in such a way that it can be recreated with the eval statement. eval evaluates a string as a Python expression and w orks much like the interactive interpreter._repr_is called when you use back quotks or call the repr command. Here's what it loote like The__str__method is a way to do a nice looking string for printing. It's called by the str () built-in function...

Running Jython

To run JytPoy for the first time, type Jython at tPa prompt, and press Enter. You sP uld see something like packageManager processing new packageManager processing new packageManager processing new packageManager processing new packageManager processing new jar, Jython 1.1 on java1.3.0 (JIT sunwjit) Copyright (C) 1997-1999 Corporation for National Research Initiatives Then press Ctrl-D to exit interactive mode. If you want to parts of the staslata Python library that aren't includes with...

RunReport

BherunReport () function uses reportStatistics () to get and print the ryport dictionary. house_in_awahtukee 100000, 120000, 150000, 200000, 65000, 100000 report range_format Range The least expensive house is (min)20.2f The most expensive house is (max)20.2f The range of house price is (range)20.2f average_format Averages The mean house price is (mean)20.2f The mode for house price is (mode)20.2f The median house price is (median)20.2f print range_format report ranges print average_format...

Scripting Versus Programming Languages

There's a fine line between scripting and programming languages. For example, Smalltalk is an extremely Yysimic isierareieY ianffffe, kfi it's soi for scri tisf. A true scri tisf ltsettee, fsiife Smfiiifif, must em ioy 1tie-kotsY oiymoraTism ind Yysimic iopisu. Mary UNIX programmers program in C ard C++ ard glue modules togethei with higher-revel shell programming (Kors, Bourne, C, etc.). Or they use tie scripting larguage Tcl for both programming their GUIs ard gluing together tieir C++...

Sequences of Characters

The sequence is used for sltn ration and means or. Its purpose is delimiting multiple subexpressions. The main expression matches if any of the subexpressions match. The metacharacter has the form < expression The following expressions both return a match object > > > > > > search(a pet( cat dog)*,I have a pet dog) This expression also matches i > > > search(a pet( cat dog)*,I have a pet) This expression returns dog > > > mo search(a pet( cat dog)*,I have a pet dog)...

Simple File Operations

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 with throughout the chapter. 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 Say, for example, thatyouwantto opena file in c dal and w rite Hello World to it. Here's how to do that. (Start up the interactive...

SQL Data Types

We've defined a few simple tables win the ddl.py module. Now let's look at the different fields that can show up in a table. Until now, we've b een using only two SQL data types, CHAR and INT.Table 17-1 lists toanh more, most of which are simular to Hose in Java and Pytno n. If you wann do know what each type laodds, an SQL reference can tell you. Table 17-1. JDBC, Java, and Python Types Table 17-1. JDBC, Java, and Python Types Notice that the left column in the table is headed JVBC, not SQL....

String Dictionary

Another useful Python feature for formatting strings is StringOperand DictionaryOperand. This form allows you ho custonuze and prinh named fields in the string. (Income ) d formats the -value referenced by the Income key . Say, for example, that you have a dictionary like the one here Occupation Chef, Name Monica, Dating Chandler, With (Income ) d, this is expressed as > > > (Income)d Monica '40000' Now let's say you have three dest f hadS) whom you define as dictionaries named...

Strings Bad Style for Exceptions

The use of strings do raise exceptio ns has fallen out of favor and will likely be phased out o f the language. The more Pythonieany correct method is to use a class instance , which we'l l xover a little later. I used the seing example here because strings are easy to define and thus make it easy to illustrate exceptions. Here's how we can modfy our figurePercentage () example to handle and reraise (throw) an exception we've already defmeg numerator tuple 0 denominator tuple 1 percent...

Syntax and Sequence Errors

If you followed along with the interactive sessions if previous chapters as recommended, you ran into errors, most of them involving seftnx (I know I have). Here's nn example > > > for x in xrange(0, 100) . Traceback (innermost last) (no code object) at line 0 File < stdin> , line 1 UsingSyntaxError invalid syntax as a clue, we discover that we forgot to put the colon at the end ofthe for heaPer. There's sot much you cnn So about seotnx errors except fix them. As you lenra Pethoo,...

The Dialog Class

The dialog class, AddAddre ssDialog, is in the same module as AddressMain and contains an instance of the AddressForm panel. It extends j ava . awt . Dialog. from java.awt import Dialog class AddAddressDialog(Dialog) AddAddressDialog gets most of its functionality from 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 is placed in the south region of the panel. The AddressFormPane inatance is...

The except Clause

Notice that the program in the example above doesn't stop midway in its iteration through the list. Instead, it prints out that there waa an error in one of the percentage c cfti ons and continues on ias way. The manic to this is the try statemtntwiehthe exceptclause. numerator tuple 0 denominator tuple l percent numerator denominator print (The percentage is + 'percent') except ZeroDivisionError print (percentage error) In English this says, Try to execute these statements. If the ZeroDivi...

The for Statement

Thefor statement repeatedly executes a suite of statements as it iterates through the items in a sequence. It appears as The expression should be a valid sequence (a tuple, string, or list). At the beginning of each iteration, the next item in the sequence is assig d to the item vaTiable, and the suite ie executed. TWs continues until all items have been dealt with. To illustrate for, let's say that we have a list of email addresses for a monthly newsletter. > > > email_list adam_s_carr...

The Full addresspy Code

Now it seems that we have everything we need to run our progrew, but first let's see all of address3.py, including the scaffolding code. This class represents an entry in an address book Constructor def _init_(self, name , phone_number , address_lines ) The constructor takes three arguments name to hold the persons name (st phone_number to hold the persons phone number (st address_lines to hold the address of the person (l assign the name, phone_number and address_lines __name, _phone_number,...

The Java Way of File Operations

Interfaces and clesses for- dealing wei iles and other I O types ere in the java.io peckege. An interface is e class thet contains abstract methods. Clesses in java.io form a class hierarchy. Tie two main class types in javaJo are text oriented (cfaracter strefmst and binary oriented (byte ytreams). Subclasses of the Reader end Writer classes are text oriented tiiose of the InputStream and OutputSt ream clayses are binary oriented. InputStream and OutputSt ream are abstract that is, tley can't...

The Jython Version

From javax.swing import JFrame, JButton, JLabel from java.awt import Font sayHello JButton(say hello, mnemonic 'h') self.contentPane.add(sayHello) self.visible 1 self.pack() sayHello.actionPerformed self._sayHello helloFrame JFrame(Hello Frame) helloLabel JLabel(Hello World, font Font(Arial, Font.BOLD, helloFrame.contentPane.add(helloLabel) helloFrame.pack() helloFrame.visible 1 frame MyFrame(title My Frame) Notice how well Jython integrates with the JavaBean properties and event model. Also...

The Limits of Inheritance

It may look like one, but inheritance is no silver bullet. In fact, there ant ry asons to limit its use. Like all good things, inheritance should be used in moderation, primarily to avoid coupling between subclass and superclass. There ant two forms of inheritance imptementntion and moerfnce. Remember that the implementation of u class is otte of the things we fry to hide with If you're going to do imp lemeftntlof inheritance from n wenkly written base clnss (superclnss), watch out if a base...

The Match ObjectA Brief Introduction

In Python, when a match is found a match object is returned. The match object and its properties will be dealt with later, but we'll give it a brief look here. Here's our salary example compiled and matched against the list of classifieds, now with some added records and capturing the match objeat Pot later use. > > > classifieds School Teacher salary 20,000.,Engineer salary is no object,Bicycle Racer salary 75,000,000. > > > for ad in classifieds mo mino.search(ad) The output is...

The Python Way of Handling Events

The following brief interactive session highlights the Python way of handling events > > > def closing(event) . . . print windowClosing > > > def closed(event) . . . print windowClosed > > > def open(event) print windowOpened Import a JFrame, create an instance of it, and configure the instance. > > > from javax.swing import JFrame > > > frame JFrame() > > > frame.title JFrame frame > > > frame.size 200,200 Set the event properties of the frame to the...

The try Statement

Thetry statement specifies a way to 0anCle exceptions. One Oorm is the following which can have one or many except clauses the exception handlers. If an exception occurs in the try clause's suite of statements, an exoep0ron handler that best fits h will be invoked. An except clause that doesn't have an expression target can act as a catchallbucket. If an exception doesn't have a specific exception handler and an except clause without an expression target is present, the exception will go to...

Thejinfo Module

I've created a module called ynfo that allowa you to inspect Java class event properties. Let's look at JButton (j avax. swing . JButton). Import the jinfo module and the JButton cIsss. > > > from javax.swing import JButton Use the getEventsInfo () method to view the events asseciated witw JButton . > > > getEventsInfo(JButton, 1) > > > Nothing happened here because the events associated with JButton are defined in JButton's superclass. Thus, we need to find out what that...

Two Ways to Look Up Events with One Method

This one works best on Windows 98 because it pauses after each event > > > from java.awt import Window > > > jinfo.getEventsInfo(Window, 1, 1) This one works best on Windows INT because you can scroll the DOS box to see the results > > > from java.awt import Window > > > jinfo.getEventsInfo(Window, 1) Table 13-1. Frame, JFrame, and Window Events The user is requesting to close the window a good time to see if the user wants to save any unsaved data. The window is the...

Type Checking callable type

Thecallable (object) function returns true if the object can be called like a function. Since mora than object types can be callable ( lambdas, functions, methods, class instances, etc.), this feature is very useful. Here's au example TOis is sice, but Oow do you use it Let's sty thet you want to fisd out wOicO objects is the currest module are ceneble. Define a class whose instances aro callable. Define au instance of the callable class. > > > hello myclass() Define some not so useful...

Unpacking the Sun Package

Here we're using J2SDK v.1s3 asKl the selfl-axtrbcting biyysy package Q2sdk-1_p_0tlmun.bin)). I pa sttell, as the root, or using the su command, copy or move the downloaded file to the directory of your cPoi ce again we're usinguser local lib, so) thb J2SE suddiIaceory is user locaf ttP jdlt 1.x. Make the file executable with the command chmod a+x j2sdk-1_3_0-linux.bin Execute it with the command . j2sdk-1_3_0-linux.bin TPis lyyyrhes a script and displays the license agreement from Sun (which...

Using DML

To show how DML works, we'll usg it to insert soimg departments into our Department table . Define a Python format string. Define a set of tuples, departme nts, for sample departments. (100, Engineering), (200, Marketing), (300, Human Resources), (400, Manufacturing) ) End of departments Iterate through departments, and create rows in the Department table. insert d_insert dept print insert statement.execute Update(insert) Now we'll add employees to the Employee table. Define an insert format...

Using Java Streams to Work with Memory

We spoke earlier about streams being abstrac t metaphors for files or, mo re precisely, any type of input output 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 leading and writing to and from memory. You might want to look them up in the Java API documentation. Instead of passing a file stream to a stream derimation, you can p ass a byte array stream. Here's...

Using the Java APIs

To see how easy it is to use the Java AP Is, fonow along with tOi s interactive session. Import two classes from the Java package jnvnx.swingo JFrame and JButton. (We'll cover theso clneses in depth in Chapter 13.) > > > from javax.swing import JFrame, JButton > > > button JButton(Hello Java APIs) (Note tOet you creete Jene instances and PytOos instances in tOe seme wey.) Add tOe button instance to the content pare. > > > pane frame.getContentPane() get access to the content...

What Are Applets

Applets represent a way to deliver safe code for producing lively Internet GUIs. They execute within a browser and are associated with (i.e., embedded in) an HTML page, so they must be inlierently portable to run in a variety of browsers on a variety of platforms. Let's rewind a bit. Applets execute within a browser, which means that code that somebody else wrote is running on your computer. That may sound dangerous, but applets can run only inside a security sandbox, which won't allow them to...

What Does It All Mean

Basically tPtt PytPoy is the best scripting language for the JVM. Here's why Ease of use. Python was designed to be easy for begiphets. In Virginia, Pigtc school students art taught how to program with il. Embeddability. On a scale from 1 to 10, Python scores 10 for embeddability. Resemblance to phe paoent lenguage Jython is syntactically identical to Python. Features. Python has some of the test features of S malltalk, Scheme, Ico n, and Java. String parsing. Python has Praties for tegytft-at...

Working with Applets

Let's start off with an interactive session. Import Applet from the java.applet package. > > > from java.applet import Applet > > > applet Applet() An applet is a parti (j ava . awt . Panel), and, as we learned earlier, a panel is also a codaonent. > > > applet.class.superclass < jclass java.awt.Panel at -731859681> So, if ar applet is a parel, ard a parol is a component, ar lopeer is ilso a component (ard tints o component container). That meases that eveIatlling you've...

Working with Java from Python

The following interactive session shown how to import and use Java classes from Python Import the Frame class from the eava.ywt pLc ge. > > > from java.awt import Frame Create an instance of Frame, named frame. > > > frame Frame(My first frame created in Jython) Import the Button class from java.awt. > > > from java.awt import Button Create an instance of Button, called hit_me. > > > hit_me Button (Hit me ) Create a handler for Button (the event handler is just a...

Write and readline

In our c dat hello. txt example, wc wrote three strings. Then we used a texd editor to read that file and saw that 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 statdand-slze file wens written on tye oame line, the file would be hard to read and parse. To avoid this, we can write a newline character ( n) at the end of each lite to denote that the text that follows begins a new lite. Let's continue with some examples that...

Writing Out Objects with pickle

With the pickle module you cop do more that fusl write out class instances to a file you can write out any PytOos object es wall. > > > file open(c dat pickle2.txt, w) Create a dictionary, populating it with a string, au integer, a float, a list, and another dictionary, aud write it to a file. > > > dict string string add a string to the dictiona > > > dict int 1 add an int to the dictionary > > > dict float 1.11 add a float to the dictionar > > > a list to the...