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 a Main Window First

We're going to create the main window for the address book application, which will have the list on the left side of the frame when the usee selects an item, it appears in the AddressForm instance on the right side. To do this we'll convert AddressForm so that it extends j ava. awt. Panel instead of j ava. awt . Frame. We'll also need to add some code to initialize the text fields in the AddressForm class (in AddressFarm.py) so that every time an address is passed to Addre ssForm (that is, when...

Adding a Main Window for the Address Book Application Prototype

The main window will have a fet of name s from the addrs ss book. As you selcct a name from the list, an AddressForm insSbfce pops up unwlndiyou edit the Address instance corrstdondrrcg to that name. As a rule, code written to access data shouldn't be in the same module with code written to build GUIs, so first we have to break our code into separate modules AddressForm.py holda the AWT versron of AddressForm Address 7.py holds the address daga code AddressMain.py holds the mein window of the...

Adding an Input Form for an Address Entry First

At this point, you probably feel comfortable with the concepts the prototype introduces. To incorporate these concepts into the address book program, let'n organize our code into a class called AddressForm. This class extends the j avax . swing . JFrame class, which makes it a JFrame. AddressForm is passed an instance of the Address class in its constructor. okayHandler () populates the fields of the instance wi h values extra nd from Addre ssForm's text fields. Look at Address6.py below and...

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...

Adding Event Handlers

We could improve our form boy setting the labels' alignment to the right, but pretty interfaces are only the start. 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 component data but only print it to the conso le. To set up the event handler for the OK button, we need to define an event handler thac take s one argument to hold the event. Create a function that acts as an event handler for the OK...

Adding Property File Support

Let's add a function ta AddrestDBUti ls.py that uses j ava .utils.Propertiesto saad tiie JDBC properties. Let's also add some eoor rec overy and some bullet-proof fuuctionality to check if the file exists and to create one if not. As an exercise, try editing the properto file from AddressDBUtils.py. Also try deleting the file and then running the module (don't forgee to back up the file first). W oat happsns Here's the latest version of AddressDBUtils.py from java.io import FileOutputStream,...

Adding the Toolbar

Remember that the dialog is opened in responsa to a click of 1Ss2 Add dutton. Lem'e take a looks at Add in a partial listing of AddressMain with ehe toolbar amded. Call the base class constructor JFrame._init_(self, Main Frame) add it to the NORTH border of the container. toolbar JPanel() self.contentPane.add(toolbar, BorderLayout.NORTH) Create two buttons addAddress JButton(Add) removeAddress JButton (Remove) Add the buttons to the toolbar toolbar.add(addAddress) Registers the buttons event...

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 Bitwise and Shift Operators

If you lack experience with any programming language or with Boolean algebra, you should ignore bitwise operators. Another reavo n to ignore them is that tieey're usually ass ociated with tow-level pro gramming, 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. Just for the sake of completeness. Table 3-4...

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...

An Event Frame

Let's create n frame that n nales every possible event thnt is, essentially, one frame thnt n nnles evetr evefl mentioned in the last section that Frame supports. We'll use the Frame class injava.awt (from which Swing gets much of its behavior and design). Examine the source code closely (it's from FraneEvents.py). Later we'll from java.awt import Frame, List, Panel, Button, FlowLayout, BorderLay Frame._init_(self, Event Frame) self.event_viewer event_viewer self.layout FlowLayout()...

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 > > >...

Behavior

An object's behavior is determine d by methods nefiaed by hs clnss Let's return to the Car class example and addstart and stop behavior. make model color Here aro some examples of the Car class methods followed by their output car Ca r() car.color Red car.make Ford car.model Taurus print After Start , car.color, car.make, car.model, car.running print After Stop , car.color, car.make, car.model, car.running After Start Red Ford Taurus l After Stop Red Ford Taurus 0

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 BuiltIn Functions

Namespace dir(), globals(), locals(), vars() Type Checking callable(), type() Operations Advanced Topic Functional Programming Advanced exec and eval Summary Built-in (intrinsic) function A good part of the simplicity and elegance of Python comes from its built-in (or instrinsic) functions. Many of these are longhand for other opeaators for egample, the cmp () function, which performs the , > , < ,< , > operations, and the repr () function, which back-quotes an object. When there's no...

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 Graphics and Events

A Quick Tour of Common Events Putting Things Together A Drawing Program The Complete Shapes and DrawShapes Modules Coupling Encapsulation Event-driven programming Event model Graphics object Hit testing In this chapter, we'll learn the basics of events and graphics. These are the things you'll need to know when you write your own graphical components. In particular, you'll need to understand the event model and some rudimentaiy graphics programming. In a later chapter, we'll see how to package...

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 SQL and JDBC

A Quick and Dirty JDBC Session Programming with JDBC and SQL SQL Data Definition Language SQL Data Manipulation Language Putting It All Together Adding Database Support to the Address Book Application Summary ANSI SQL autoexec.bat file Class path Database Database-aware dictionary Data Definition Language Data Manipulation Language Dirty flag Foreign key Garbage collector Java Virtual Machine JDBC Main block Primary key RDBMS R efierential integrity Setter m ethod Structured Query Language try...

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...

Classes and OOP

Like their counterparts in other languages, cla es in Python are collections orfvariables and the methods that operate on them. To iUustrate, here's an example class, Car, that inSerto from the two othar classes, > > > class Automobile pass > > > class Car(Automobile, Transportation) def _init_(self, make, model) print similar to a destructor str Make + self.make str str + , Model + self.model We can create an inslance of Car and call it car. > > > car Car(Chevy, Nova) Create...

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 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...

Converting Strings to Numbers float int long ord

Thef loat() function converts a string to a float. > > > f float (1.1) > > > type(f) < jclass org.python.core.PyFloat at 1662336> > > > Theint () function converts strings to integers. > > > str 1 > > > num int(str) > > > type(num) < jclass org.python.core.Pylnteger at 3414368> > > > Thelong () function converts a string into a long. > > > long(12345678901234567890) 12 345 67 8 901234567890L Theord () function converts a character (that...

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.,...

Document Strings

Document strings are literals that you put at the beginning of modules, functions, classes, and methods. Unlike comments, they're not thrown away but can bg ditplhyed prom the interactive interpreter. The following example (comments.py) shows a document string for a module, a class, and a function, respectively. (We'll get to these in Chapter 5.) Example showing a module document string for the comments module. T module document string is multi-line. Example showing a class document string def...

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...

Dont Overdo the Comments

I don't recommend using comments as I have here whcnyou're writing real code. For more on writing comments and maintainable code, read Ensugh Rspt ts Shsst Ysurstlfin tht Fsst (Holub, 1995). from javax.swing import JFrame, JList, DefaultListModel from java.awt import BorderLayout from address7 import * from AddressFormPane import AddressForm class AddressMain(JFrame) def _init_(self) Call the base class constructor JFrame._init_(self, Main Frame) Create a list. self.addresses...

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...

Encapsulation with Private Variables

One of the things that separate classes from records or structures in other languages is the concept of encapsulation. Encapsulation hides the implementation deinils of your class and in doing so reduces code coupling. Coupling is bad. Let's say, for example, that you create a simple address book class that downloads all of the addresses from a corporate database asp stores them in a lisa cplled name s. Other programmers who use your class simply access this names list. Well, imagine that tha...

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...

File Interactive Session

Import the File class from the jmvtt.io pa ckpge. > > > from java.io import File Create an instance of the file obped that nefers to the properties of the file (c dat File. txt). > > > file File(c Xdat XFile.txt) Determine if the file is read-only by calling canWrite (). If canWrite () returns 1 (true), the file is read write. (If you change the erop)ertits of the file to read-only, canWrite () returns 0, that is, false.) Determine if the file...

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 >...

Finding Fonts

> > > from java.awt import GraphicsEnvironment > > > ge > > > fontlist ge.getAllFonts() > > > len(fontlist) 98 > > > for x in range (0, 10) print fontlist x .name 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 then havp simltbr characteristics. > > > families ge.getAvailableFontFamilyNames() > > > len(families) 62 > > > for x in range (0, 10) print families x...

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...

Format Directives

Table 3-6 covers all of the format datives 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) . > > > list hi, 1, 1.0, 1L > > > s list 'hi', 1, 1.0, 1L > > > list equals s list list equals 'hi', 1, 1.0, 1L > > > i i (5) 'i 5' > > > i 3i (5) 'i 5' > > > d d 5 'd 5' > > > 3d (3) ' 3 ' > > > x (0xff) 'ff' > > > x (255) 'ff' > > > x...

Formatting Strings Modulus

Although not actually modulus, the Python operator works similarly in string formatting to interpo late variables into a formatting string. If you've programmed in C, you'll notice that is much likw C's printf () , sprintf ( ), and fprintf ( ) functions. There are two forms of , one of which works with strings and tuples, the other with dictionaries. StringOperand TupleOperand StringOperand DictionaryOperand Both return a new formatted string quickly and easily.

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 Rid of n

You may want to dispose of the new line character when you read in a line. Here's the not very Python way of doin this > > > f open( dat data.txt) reopen the file again > > > line f.readline() read in the line > > > line before removing the newline character > > > line line 0 len(line)-1 chop of the newline character > > > line After the newline character is gone. > > > f.close() close the file > > > f open( dat data.txt) > > > line (f.readline())...

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)

Insert

If tables are like classes rnPython, then sows ure like i sances. Since the INSERT etatement inserts values into a table, we can think om it ns analogous to calling a constr-uctos, that is, ceeating an in ance of a recobd (valuel, value2, ) Here it's adding values to the Employee tab le (10507, 'Bob Jones', '1', 10) Select interpreters, and compilers TheSELECT statement selects rows from a table. We've already used it, so I won't belabor it at this point. Here's its form GROUP BY table.field,...

Installation

If you have any problems with installation, report them to j ython-dev lists . source -forge . ne t. (Tell them I sent you.) Make sure you've done everything you can before reporting what might turn out to be a nonproblem. Y ou may discover that your problem is unique to your platform. To find out for sure, go to www.jython.oig platform.html. They'll let you know. To rts your YowiilotYeY file, go So ite directory thai TolYs ite OyiTos library file, ant run itis if ite comminY line C temp>...

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...

IO Classes to Be Covered

There ere more than thirty I O clesses, not including interfaces and abstract clesses. This seems like e lot, but if you understand how Reader,Writer,InputStream, and OutputStream work, you can easily understand tie rest. Reader end Writer subclesses deal with character streams, thet is, text. InputStream and OutputSt ream subclasses deal with binary streams. An easy way to remember this is, if you can read it, use Reader end Writer if you can't, use InputStream end OutputStream.

Java Arrays and jarray

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 likely candidate for an array, but that's not exactly the case. You see, an array is like a homogeneous tuple or list every item in it is of the same type but a tuple is heterogeneous items in it can be of different types. A lot of Java methods have Java arrays as...

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...

Numeric Operations cmp divmod pow abs round

Cmp (x, y) compares two numeric sypes. It usso wo cksfor sequences, dictionaries, and other numerk objects. cmp () returns a positive numbee f the x argument is greater than the y argument, a negative number if they argument is greater than the x argument, and 0 if x andy are equal. cmp () is related to the equality operators ( ,> ,< , etc.). If you want these operators to work with class instances, you need to implement cmp () for the class by executing cmp (instance1, instance2),...

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.

Persisted Data

Writing to files without reading them doesn't do you much good unless you're creating a report of some kind. If you want to persist data so you can use it laher, you have to be able to read ip back into the pro gram. Here's how we read the data that we wsoie in tlie fipet example (please follow along) > > > file open( dat hello.txt, r) There ad () method returns a string representing the contents of the file.

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,...

Preface

Python is a dynamic progtamming langunge with the powen of well-known lamguages such as Java, C++, and Smalltalk. In fact, Python is leaner and meaner than any ef these longuugos and yet very expressiva it doesn't talk much, but it has e lot to say . Python has another plus the oimplicity om eanguages such as VB Script and JavaScript, which makes it easy for beginning programmers to learn. Novices who know their way around a computer can pick it up quickly, particularly if they have ever...

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 It All Together

Let's show DDL in achon by running the Acccos ddlpy module , which defines DDL staaement strings and then executes each one with thk JDBC statemenc o ert's executeUpdate () method. from java.sql import DriverManager from java.lang import Class Class.forName('sun.j dbc.odbc.JdbcOdbcDriver') url jdbc odbc db_dev connecti on DriverManager.getConnection(url, , ) statement connection.createStatement() create_department CONSTRAINT DEPT_PK_KEY PRIMARY KEY (DeptID) CONSTRAINT EMP_PK_KEY PRIMARY KEY...

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...

Putting Things Together

A third-party eeedor I (Rick Hightower) worked with oece had a proZlem reedieg the IDL files we were tryieg to ietrgrrtr with its product. hpncifrcallu it dide't like idretifitrs Zngiefifg with , as ie com mycompany Employee, prnfnrrieg com mycompany Employee. My joZ was to convert the IDL file s to their liking, which I did using regular expressions. The code I wrote to do this is just four lines long (actually six but four with a little cheating). Here's the oude to read in the file hnd write...

Putting Things Together with JCheck

Here's the pizza topping application we just wrote. Follow along, and make sure to read the comments. Import JCheckBox and create checkboxes that represent pizza top from javax.swing import JCheckBox cb is the JCheckBox class. Remember classes are first class objects i pepperoni cb(pepperoni) checkboxes ,cb(c ,cb(sausage)) Import JFrame and create a frame to hold our checkboxes. from javax.swing import JFrame frame JFrame(title Pick your topping, visible 1) Import JPanel and set the frame's...

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++...