Quick and Dirty JDBC Session

Naturally I don't know what database you have access to, ro on this b ook's Web spe I'm u sing two stardaads Microsoft Access ard va I nstartDB. The exercises should wook with any SQL dathbase) as tong as h has JDBk support. You may have to eweak che statements a little, but after this chapter you should feel comfortable with that. For Microsoft Access weye going to use the JDBk-ODB k bridge, which mtegrate s ODBk- compliant databases with Java applications. pODBk stdnds foe Open Database...

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 an Input Form for an Address Entry The Prototype

In an interactive session, let's create a GUI form that can edit an address entry. We want a frame that holds text field components, whichwillbe used to gathertlie address information. We also want an OK button, which signifies that the user is done entering the current address. To get the layout for the frame cowponents, we'll use a technique that layers components in a container. For this we'll put the text fields in one panel and the OK button in another. The panels themselves are components...

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 Components to the Frame

To illustrate edding compoiitnts to hhe frame, we'll import some components from AWT. Then we'll create and edd e button, e label, e checkbox, and e text field. > > > from javax.swing import JButton, JLabel > > > from javax.swing import JCheckBox, JTextField > > > Add e lebel component. > > > Add e checkbox component. > > > ) Add e text field component You mey think thet our frawe skould be shgwi ag some components et this point, but it won't until we tell it to by...

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

Advanced Topic Applet Context and Applet Stub

When an applet is created, it's given a stub via its setStub ( ) method. The stub is the interface between the applet and the brywset. You don't have to deal directly withthe stub because the Applet class implements methods that use it. appletResize(width, height) resizo the apple getAppletContext () fep the applet's cohtext getCodeBase() gets the code base URL getDocumentBase () gets the document base URL getParameterName () gets ay applet parameter isActive () determines if the applet is...

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

AWT or JFC

If you can't control the client that is, what browser he's using you may want to use AWT. You'll probably also use it when you're working with hand-held devices. Even so, JFC has many features that have no AWT equivalent, so it's a better general-purpose tool. Actually, JFC encompasses both AWT and Swing, but Swing is the newer, so-called lightweight version of GUI widgets (components). Basically, Swing widgets have no operating system counterpart. Learning GUI programming in Java is a fairly...

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

Button and JButton Shared Properties

Using the enabled(Boolean b) property, disable the AWT and JFC buttons. > > > button.enabled 0 You'll notice that the buttons' text is grayed out. If you click on them, you won't get any action event. To enable the buttons again use There are some things you s an do with j ava .swing. JButton that you can't do with j ava . awt . Button. For one, wish the mnemonic (char mnemonic) eeoperty you can s et the button so that it receives input focuc when you press n shortcut key. You can set up...

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 in Address Mainpy

As for what's different in AddressMain.py, the most obvious thing is that all of the code is contained in a class. We created an instance of AddressForm and added ic to the main frame. Create the AddressForm and add it to the EAST. self.form AddressForm() self.container.add(self.form, BorderLayout.EAST) Another difference appearo in the lis t eve nh hmdler. In the prototype, we caeatea a new instance of AddressForm and passed its constructor an address instance from the dictionary. Here we...

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

Chapter Working with Strings

Case Crabet capitalize), capwords(), swaecasts(), lowerO, ueett() Fibaibe findO, tfiba(), indexO, tibatx(), countO, replace() Selittine and Joibibe splitO, splitfields(), join(), jomfieldsO Sttieeibe abaPatsibe lsttie(), tsttie(), strip() Aajustibe Text ljust(), tjust(), centerO, zfill(), txeabataas() Summatd Sooner or later, you'll need to format, parse, or manipulate strings. For these tasks, you'll likely use the functions in the Python string module. Spend some time familiariging yourself...

Class Instances

Say we want to create 20 chapter classes. To do this with what we've learned so far, we'd have to redefine chapter 20 times. Time consuming, ista it Whhwhat wege about to learns, we caninstead create an instance of chapter for each chapter in our book. Think of a class as a cookie cutter ass am instance as vn actual cookie. You use the cookie cutter to stamp the cookie out. With claises, snappping out the class instances is called instaiitinrion When a class is isstnntinteS, the instance shares...

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

Cmpand Equality versus Default Object Identity

If we don't define__cmp_, tOa comparison of objects won't work. To prove this, let's do a small > > > class classl . . . var hi > > > instance classl () > > > instance2 classl () TOe isstnnces 0eee the same values, yet wOes we compare them tOey tees't equal (e 0 vatue equals false). > > > instance instance2 0 The default operation for__cmp_is to check for obj ect idenMy' Thus , if we suc anotOar instance to equal the first and then tost for equality, we get a true (1...

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

Common File Methods

The Python file object supports the methods shown in the following list read() read in data from the file readline () read a line of data from a file readline s() read all the lines in the file and return them as ample of stpings write() wpite daoa to a eile writelines () write atople of linee to a fole seek() move to a certain point in a mile tell() deCe bine the cdrrent lo cation in the file This is only a partial list. You can read about other file object methods in the Python documentation.

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

Components and Containers

In Java, you organize compontitis as nest ed elements. Typically you have at frame, which contains several panels and maybe a toolbar and a menubar. In fact, each panel can contain other components such as text fields and labels or even other panels, so a complete graphical user interface can consist of many nested elements. The JFC and AWT containers arc components themselves and can be contained in other containers. You can see this in their class diagrams, which also show their points of...

Control Flow

Python provides ill of the control flow constructs (discussed in Chapter 4) that an experienced programmer is used to if, while, and for. The ony difference between these constructs in Python and their counterparts in other languages is their use of indentation to define code blockt. Here's t simple i f statement. Note mat, unnlike Java, Python uses numerics as Boolean values thus, any nonzero value is considered true. Here's a more complex i f sfatememt that uses elif (else if) and else blocks...

Conversion atoi atof atol

Atoi (s , base ) converts a string into gn mte r. The defa ult is decimal, but you can specify octal 8, hexadecimal 16, or decimal 10. If 0 is the base, the string will be parsed as a hexadecimal if it has a leading 0x and as an octal if it has a leading 0. Otherwise, it will be treated as a decimal. Let's do an example. In this and all other examples in this chapter, you have to first import the string module from string import *. Convert 1 to an integer. Convert 2 5 5 to a base 10 integer....

Converting Numbers to Strings chr str hex oct

Thechr () function converts e number to e character. Remember thet there ere no characters in Python, so chr() returns e single cherecter in e string. It may seem that you would rarely use chr(), but wait until Chapter 12, when it will come in handy for converting a Java binary array into a Python string. Thestr () function converts any object, including numeric types, into a string. (Remember, unlike other languages Python treahs all types as objects.) Thehex () function converts a number into...

Converting Objects to Strings str repr

Thestr () function converts all object types to strings. The repr () function converts all object types to strings thet might be able to reconstruct the object with e call to eval. Here's an example of both. Create e list, e tuple, e string, and en integer object. > > > list, tuple, string, int 1,2 ,(1,2),12,12 Create e dictionary object thet contains the list, tupli, stfing and integer objectsj uet seated > > > dict list list, tuple tuple, string string, int 12 Show the string...

Converting Sequences list tuple

Remember that tuples are immutable, which means ohat you can't add items to them Iu you nwed ko add items to a sequence, you have to use a list. Conversely, you can't use a list as a key into a dictionary. Since dictionaries store items based on a hashtable that uses the hash value of the key, they need types that won't change that is, immutable tuples. Python has two built in functions to deal with these problems. Thel i s t () function converts an immutable sequence (such as a tuple) into a...

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

Declaring Variables

In most languages, before you can use a variable you have to declare it that is, you must assign it a name and a type. Python is different unlike in other l meuhees, fou dechtt a variable implicitl. by assigning a value to it. Here's at example declare age to be of type integer and of value 28. age 2 8 declare name to be of type string and of value rick name rick Variable declarations cat go anywhere in a module. You cat declare more than one variable at once by stringing them together. (Follow...

Default Layout Manager

The default layout managee for the frame is BorderLa yout, which essentially allows you to add components to a frame's north, south, east, and west borders and its center region. We'll cover it and the other layout monagers in Chapter 14. Now we'll create a toolbar, using a panel and two) buttons, tnat will allow us to work with the text field's properties. Import Panel, and create a panel for a toolbar. > > > from java.awt import Panel > > > toolbar Panel () Create two buttons for...

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

Exception Handling

Like so much of Python, exception handling is a iot like its counterparts in otheo languages . For example, Python'stry clause is like Java' F try, and its except clause is like Java's catch. Consider an exception thrown by a dictionary object if we try o no) nexistayt key. In thin cnse, the interpreter simply prints the exception out to the screen. > > > diet Green Eggs Ham > > > diet Blue Eggs Traceback (innermost last) File < console> , line 1, in KeyError Blue Eggs To handle...

Exception Hierarchy

Using the class approach, you can build a hierarchy of exceptions. This allows programmers who use the methods of one of your classes to decide the level of detail or granularity they care about. For example, you can define 30 CarException classes that can be thrown when the Car class starts that is, when someone calls the class's_start__method. One user of your Car class may care about all 30. Another may care only if anyCarException is throwp and therefore write an except clause only to catch...

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 Support

The next thing we do is proride file support for our program by adding the_s ave__method in the Address clnss. Taking a file object as an argument,_save_saves members of the class instance to a file. The following, from address2,py, shows Address . save file.write(self._name + n) file.write(self._phone_number + n) if there are address lines then write them out to the file file.write(true + n) file.write(self._lines + n) As you crn see, save writes akl og the membest of De clast. The code checks...

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

Fo r Beginners Understanding Streams

Think of e stream es an ebstrect filey Jusc es you can reed and wrote tp e file, you gen re ed and write to e stream. You might use v stream for- reeding and writing with an RS-232 serial coimection, e TCP IP cofkectio n, or e memory location (like e tequence) . A stream is obstract, so if you know low to read and write to a file, you basically already know low to read and write to a memory locetion or an RS-232 serial connection or, for thet matter, e Web site. This is the art and megic of...

For Programmers Hashtables Vectors and Collection Objects

If you use Java, you probably use yhsytables and vectors in about 85 percebt of the programs you write. Hashtables ate sianilhr to Python dictionaries, and vectors are similat to Pyiyob lists. The key difference is that Python's lists, dictionaries, and tuples have built-in syntax support for addition, multiplication, member referencing, literals, for loop iteration, and so forth. This makes things easier on the programmer. It also means that you can define objects to act like collections so...

For Programmers Implicit Variable Declaration

In Python variables are implicitly declared. That is, the fire time a variable is used it is assigned a value. This assigned value determines its type. In the salary example, all variables are assigned values of type Integer. Novices, if you're reading this note and are confused by the concept of type, don't worry we'll get to it. For understanding the ideas presented in the rest of the chapter, you just need to know that numbers can be od type Integer text can be of types String,List, eda...

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

For Programmers Variable Declarations in Python as Compared to Visual Basic and Java

In Python, you can't tccess t variable that you haven't declared, but remember The first time you assign t vtlue to t variable, you declare that variable. That means that you can't make the mistake of trying to use in unissued variable, is you can in Visual Basic. Only if you don't use Visual's Explicit option can you use a variable that has no value assigned. Visual Basic has a Variant type, which en be anything. Pntnoa variables don't hive t type unto themselves but are whatever type assigned...

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

Globals and the Global Statement

The word global strikes fear in tiie hearts of object-orientsd programmers (and stt-uctured programmers, for that matter). That's because glo l variables variables that are in a global pamesycee Popi that's available to all modules, functions, and elasses) are usually a bmd IOu ng and should be avoided, Ip fact, there aren't any real global variables in Python. All variables have to be in the context of a module, class, or function. However, Pychon does havea global statement, which allows you...

Grouping and Backreferences

A very useful feature of Python regular expressions is their ability to reference (or gacPreference) text praeiously matched and reuse it. Suppose we're looking for a salary in the range of XX,XXX,XXX. We can extend our expression by adding aootpf set of d 3,3 , but, since we already have this written, we can reuse it instead. To capture the pattern we use the ( ) sequence. The piece enclosed in parentheses is called a group or a subexpression. We can use it to add another three digits to our...

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

How Modular Is Modular Enough

The sad fact is that we don't have all the time in the world to tinker with our address book application. In the real world, customers want a working product as quickly as possible, even if it's less than perfect. If we strive for perfection we'll never get it. That said, I think our code at this point is modular enough. As an exercise, review the changes in the address book opplication aud then run the new version. Remember that AddressMain.py is the mainmodfle, so to open title application...

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)

INNER Join

Most databases assume an INNERJOIN if She JOIN clause is left by itself. However, MSAccess mikes no such assumption ard expe cis you to specify ar INNERJOIN like itis as emp_name, as salary, as dept name (e . Salary > 10 ) (e.DeptID 100) The four ropei of JOIN are INNER,OUTER,LEFT, art RIGHT. We're going So cover osly INNERJOINs, which are probably tie most common. By ite wiy, you nan jois more iTas one ribe fi a iime by tYYisf exiri JOIN clius es. You car fird tie exact syntax in a good SQL...

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

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

Installing the JSEStep by Step

Before you can start installation, you need to download and install J2SE v. 1.4 (or the equivalent for your environment Linux ushrs, sire Appendix B). Jus follow the iitslntctions at rttp jeve.sao.com prsaucts jaP 1.4 . This can take a while depending ov your modem's speed. Once you have the J2SE, install the software by aouble)clicpiod the file in the airectory yah downloaded it to. During setup, accept all defaults. For example, the default directory is n j2skd1.4.0. The rest of the...

InstantDB A Little Different

InstanDE v.3.12 doesn't support the CONSTRAINT clause or foreign keys, nor can it handle the ALTER TABL though the documentation oays otherwise. Here's its version of ddl.py (InstanfDB ddl.py) from java.sql import DriverManager from java.lang import Class url jdbc idb db_dev.prp , ) statement connection.createStatement() create_department create_employee Note that InstantDB does not understand foreign keys . No understanding of foreign keys or referential integrity checking REMOVED CONSTRAINT...

Integrating Address Model with the Database

Instead of replacing the flat file, let's see how to polymorphically add the database as an option. Via the _import_function, AddressModel imports functions from AddressIO that dynamically load the I O utility module (AddressBoo1i3 AddresslO.py). from java.io import FileInputStream, FileOutputStream, IOException holds property file for the db connection info. PROP_FILE addr.props def readAddresses() pass Load the properties. props __loadProps() readAddresses module.readAddresses writeAddresses...

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 open rawinput

Theopen(filename, mode , bufsize ) function returns e file object. Again, this is just e brief review since we covered I O in Chepter 7. > > > file open( dat exp.txt, w) > > > file.write(Hello) > > > file.close() > > > file open( dat exp.txt) Themode argument specifies lond ( r), write (w), read write (r+), end eppend (a) mode. bufsize sets the size of the buffer. Setting the buffer to zero means no buffering. (For more on buffering see Chepter 12.) Theraw_input( prompt...

Java and Python

No doubt you've heard of Java, even the novices among you. Over a thousand books on it are on bookstore and library shelves, so it's hpard to mi as. Remember our discussion of compilers and interpreters Like Python, Java is an interpreted language, but, like C++, it's also a compiled language. In other words, it compiles into) an intermediate language culled bytecode, which is then interpreted into macSsiAe code at runtime (that is, when the program is put to use by the user). This makes Java a...

Java and Scripting

I ctii Jivi t scri tisf laneuiee os steroids. Is ftci, kecltse if uses statically iy eY o1ymor Tism, it's more precisely a hybrid. This may at first seem like a disadvantage, but it turns out that Java's statically typed polymorphism, as well as its design by interface, is great for systems programming, framework definition, and component development. It would be wrong to view Java as a system programming language by classical definition. Rather, it's a virtual system hroerrmmlue language for a...

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 Code That Uses a Jython Class

Here'stestOutS creen. j ava, which treats OutputScreen iye esy otter Jove cless public static void main(String args) OutputScreen os new OutputScreen() byte bytes 0,1,2,3,4,5,6,7,8,9,0xa,0xb,0xC os.write (1) os.write(bytes, 5, 5) os.write(bytes) do something useful with this exception The procedmg code needs little explanation, as alt it dres is create au mstnnce of OutputSc reen and call all tOroe forms of the overlooded write () method. To compile and run it, do this C jpybook chap11...

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

Java Event Handling and JButton

To demonstrate Java evewt handling we'll create a class tmat implfments ActionLi stener. Then, using addActionListener, wed vegister an instance of the Listener class to the button. > > > from java.awt.event import ActionListener > > > class ButtonListener(ActionListener) def actionPerformed(self, e) print e.getSource().getText() + was clicked Create an instance of Listener, and register it with the button. > > > listen ButtonListener() > > >...

JDBC Helper Methods

Helper methods do common things such as execute an update, load a driver, and create connection and statement objects. They also do error checking and cleanup. The following code illustrates some helpers. (Pay particular attention to the document strings.) Loads the driver class into the JVM. Checks to see if the class is already loaded. Class.forName(jdbc) _loaded_driver 1 error Unable to load the driver +jdbc print error raise DBException(error) def createConnection() Creates a database...

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

Jython

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

Layout Managers

If you've worked with Visual Basic or any other tools that support GUI code generation, you may be accustomed to laying out components on a form o nd specifying the size and position in pixelc. (A pixel i s 1 20 inch.) The problem is, of course, mhat you may develop your application on a 25-inch monitor, and then someone will try to use it on a 12-inch moritert leaving half ohe GUI off the screen. This problem becomes even more pronounced if you have no control over the type of displrd your GU...

Learning Python First

Learning any one programming language makes it much easier to understand not only computers but other programming languages as well. As you'll see, Python is perhaps the easiest language to learn and use. This makes it the logical one to got unden youa belt a s a first step on the my to Visual Basic, Java, and so forth. It's important to understand that not all languages are alike. Fow example, so me, such as C++, Java, and Python, areterse. That is, they get a lot done without a lot of code....