Chapter 4. Jython Classes

Object-oriented programming (OOP) is an enormous concept and unfortunately not the topic of this book. A wealth of information about OOP is available from a variety of other resources. Therefore, this chapter is limited to the syntax and semantics of Jython OOP constructs. However, consider the fact that in Jython we use scripting objects to interact with the WebSphere Application Server environment, and objects are created using classes.

Class Statement

To create an object, you must be able to define the data type for the object. To do so, use the class statement, the simplified syntax for which is shown here:

image

Like function definitions, class definitions are executable statements. When one is executed, information about the specified class is collected by Jython. Generally, the statements within a class definition are function definitions. In addition to function definitions, a class documentation string (docstring) is also allowed. As with function definitions, if the first non-blank expression statement in a class definition is a string literal, it is considered the class docstring and can be accessed using either ClassName.__doc__ or objectName.__doc__.

This use of a period ('.') after a class or object name is significant. It identifies that the name/identifier that follows is an attribute, or method, of the specified class or object. The “Modules” section in this chapter notes that this “dot qualifier” is also used to indicate that the identifier after the dot (period) is qualified by the identifier preceding the dot. So ClassName.__doc__ identifies that the __doc__ (docstring) attribute for the specified class is being referenced.

Example class Definition

Listing 4.1 shows a simple class definition for class Thing. The Thing class has two attributes (data values) and two methods (functions). Remember that even though it is not explicitly identified as such, the class documentation string (docstring) is an attribute. It is also useful to remember that methods, like functions, can also have docstrings.

Listing 4.1 Simple Class Definition

image

Also note that the name of the first parameter defined in class methods is not required to be self. This is merely a convention, not a requirement. However, using something other than self is probably a bad idea because of the potential confusion that it could cause to the human reader. Jython (and Python) programmers are comfortable with the convention of using self to indicate when the first parameter of a function (method) is used to identify the object with which the function is associated.

Listing 4.2 demonstrates how to instantiate (create) two objects of this new data type using the same notation used to execute a function—that is, to use the class name followed by parentheses. Table 4.1 explains each line in Listing 4.2 in more detail.

Listing 4.2 Example Object Creation and Use

image

Table 4.1 Example Object Creation Explained

image

Unlike some object-oriented languages, Jython does not rigidly restrict or even limit access to attributes and methods within an object. It is the responsibility of the programmer to use good sense and not abuse the openness of the language. Use the object methods to access the instance data. If your code ignores this convention, it will be more difficult to maintain. Imagine what happens to your scripts if the underlying class definition changes in some way (that is, the attributes or their types are modified). Things that were previously working now either cause exceptions or (even worse) invalid results. Exceptions are easy to see, whereas a incorrect value somewhere in the middle of your script is much more difficult to understand and locate. Therefore, it is a best practice to use the interface provided by the object methods to access and update the underlying information.

What does this mean? Generally, it means that you should not write code that “looks into” an object to access or manipulate its attributes. Use the provided methods to “get” or “set” values within the object. If the class is almost but not quite what you need, consider creating and defining a descendent class that extends the existing class to do what you need it to do.

Object Instantiation

One of the things we have yet to discuss is object customization during the creation process. In some programming languages, the terminology for a method to be executed during the object creation process is a constructor. In Jython, if a method named __init__ exists within the class, it will be called as part of the instantiation process. The syntax for this method is shown here:

def __init__( self ) :
    <statement-suite>

Note

There are no special methods that are automatically executed when an object instance is no longer needed (that is, there are no destructor methods).

Built-in Constants

You should be aware that the only “constants” in Jython are the numeric (and string) literal values. Even the “special” identifier, None, is not a constant.1 Hopefully it won’t be too difficult for you to restrain from assigning a different value to it. Listing 4.3 shows an example of how dangerous this can be.

1 None became a constant in version 2.4 of Python. It is not clear when the version of Jython that is used by wsadmin will do the same.

Listing 4.3 None Is Not (Yet) a Constant

image

image

If you were to do something silly like this (that is, assigning a value to None), someone (either you or someone who tries to make use of your script) is likely to lose time trying to figure out why scripts are not working as expected or even worse, debugging scripts that apparently worked fine previously. So be careful not to do this kind of thing.

Built-in Data Types

Built-in data types (that is, numbers, strings, tuples, lists, and dictionaries) were one of the first things covered in this book. Of these, only lists and dictionaries are mutable. Each data type is, in essence, a class. These built-in data types have associated methods that are used to manipulate the object. This section identifies and describes these methods. In some cases, sample code snippets are provided as part of the explanation or to help clarify how the method should be used.

List Methods

The following methods are available for all list objects. It is very doubtful that you will be reading this in order from start to finish, so you can use the following as a reference when you need to check what methods exist for list objects.

append( item )

Lengthen the list by adding the specified item. Logically, equivalent to:

List[ len( List ) : len( List ) ] = [ item ]

count( item )

Return the number of times that item occurs in the list.

extend( item )

Lengthen the list by adding the specified item. This differs from the append() method when the item to be added is a sequence. When a sequence is added using append(), it is added to the end of the list as an individual item. The extend() method appends each sequence element individually, as can be seen in Listing 4.4.

Listing 4.4 List extend() Method Example

image

index( item )

Return the index of the first occurrence of item in the list, if it exists. If it doesn’t exist in the list, a ValueError exception is raised.

insert( index, item )

Inserts the specified item at the indicated index position. Logically, equivalent to:

List[ index : index ] = [ item ]

pop( [ index ] )

If the optional index is specified, remove and return that item from the list; otherwise, remove and return the last item in the list. Should the list be empty or should the specified index element not exist, an IndexError exception is raised.

remove( item )

Remove the first occurence of the specified item from the list, should it exist. If the item does not exist in the list, a ValueError exception is raised.

reverse()

Reverse the list contents “in place.” Listing 4.5 provides an example of how you would use the reverse() method.

Listing 4.5 List reverse() Method Example

image

Note

This method returns None, not another (reversed) list instance.2

2 As shown in Listing 4.5 (lines 4–5).

sort( [ compareFunction ] )

Sort the list contents “in place.” The compareFunction, if specified, is used to determine the ordering of the list elements. This is especially useful when the list elements are not simple types. If the compareFunction is provided, it is called and passed two items from the list. It should return the following:

-1—To indicate that the first item is less than the second.

0—To indicate that the first item is equal to the second.

1—To indicate that the first item is greater than the second.

Note

This method returns None, not another (sorted) list instance.

Dictionary Methods

Dictionaries are also objects. Each dictionary has the following methods available to it. Again, it is unreasonable to expect you to read and remember all the methods described in this section. It is more likely that it will be used as a reference while using dictionary objects.

clear()

Remove all items from the dictionary.

copy()

Return a “shallow” copy of the dictionary, which means that the copy will have the same keys, but each value will refer to the same value object, should one exist. Listing 4.6 provides a copy() method example, and Table 4.2 explains this listing in detail.

Listing 4.6 Dictionary copy() Method Example

image

Table 4.2 Dictionary copy() Method Example Explained

image

get( key [, defaultValue ] )

Return the value associated with the specified key. If the key isn’t in the dictionary, this method returns the optional defaultValue, should it exist, or None if defaultValue isn’t specified. Conceptually, this is like the get() function shown in Listing 4.7.

Listing 4.7 Dictionary get() Method Concept

image

has_key( key )

Return 1 if the specified key exists in the dictionary; otherwise, a 0 is returned.

items()

Return a list of the dictionary key/value (tuple) pairs.

keys()

Return a list of the dictionary keys.

setdefault( key [, defaultValue ] )

If the specified key exists in the dictionary, return the associated value. Otherwise, return the optional defaultValue while adding this key/defaultValue pair to the dictionary. If defaultValue is not specified, None is used.

update( dict )

Use the key/value pairs from the specified dictionary to add or replace key/value pairs in the current dictionary.

values()

Return a list of the dictionary values.

String Methods

Strings are also objects, and have their own set of methods. Since string use in scripts is so common, we expect that this will be a frequently referenced section of the book.

capitalize( )

Return a copy of the string with the first character capitalized.

center( width )

Return a space padded string of the specified width containing the given string centered in the middle.

count( substring[, start[, end ] ] )

Return the number of occurrences of the given substring, where the optional start and end parameters are used like slice values to indicate the portion of the string to be checked.

endswith( suffix[, start[, end ] ] )

Return 1 if the string ends with the specified suffix; otherwise, return 0. The optional start and end parameters are used like slice values to indicate the starting and ending indices.

expandtabs( [tabsize] )

Return a copy of the string with all tab characters are expanded using spaces. If the optional tabsize parameter is not specified, 8 is used.

find( substring[, start[, end ] ] )

Return the lowest index in the string where the substring is located. The optional start and end parameters are used like slice notation values to indicate the portion of the string to be checked. Return -1 if the substring is not found.

index( substring[, start [, end ] ] )

Like find(), but a ValueError exception is raised should substring not be present.

isalnum( )

Return 1 if at least one character exists and all characters in the string are alphanumeric (that is, '0' through '9', 'a' through 'z', or 'A' through 'Z'). Otherwise, a 0 is returned.

isalpha( )

Return 1 if at least one character exists and all characters in the string are alphabetic ('a' through 'z', or 'A' through 'Z'). Otherwise, a 0 is returned.

isdigit( )

Return 1 if at least one character exists and all characters in the string are numeric ('0' through '9'). Otherwise, a 0 is returned.

islower( )

Return 1 if at least one letter character exists and all letters in the string are lowercase. Otherwise, a 0 is returned.

isspace( )

Return 1 if at least one character exists and all characters in the string are whitespace characters (space, tab, newline, carriage return, vertical tab). Otherwise, a 0 is returned.

istitle( )

Return 1 if at least one character exists and all characters in the title follow capitalization rules (uppercase letters may only follow non-letters, and lowercase letters may only follow letters). Otherwise, a 0 is returned.

isupper( )

Return 1 if at least one letter character exists and all letters in the string are uppercase. Otherwise, a 0 is returned.

join( sequence )

Return a string that is the concatenation of the strings in the sequence. The separator between elements is the string whose method is being used. Keep in mind that if an empty delimiter string is specified, the sequence strings are simply concatenated. Listing 4.8, on line 5, shows how the string for which the join() method is being called is a single space.

Listing 4.8 split() and join() String Methods

image

ljust( width )

Return a string of the specified width, padded on the right with spaces. If width is less than or equal to length of given string, return a copy of the given string.

lower( )

Return a copy of the string with all uppercase characters converted to lowercase.

lstrip( )

Return a copy of the string with all leading whitespace characters removed.

replace( old, new[, count ] )

Return a copy of the string after replacing a maximum of the count occurrences of old replaced by new. If count is not specified, all occurrences are replaced.

rfind( substring[,start [,end ] ] )

Like find(), but the highest index is returned or -1 if the substring is not found in the string. The optional start and end parameters are used like slice notation values to indicate the portion of the string to be checked.

rindex( substring[, start[, end ] ] )

Like rfind(), but a ValueError exception is raised if the substring is not present.

rjust( width )

Return a string of the specified width, padded on the left with spaces. If width is less than or equal to length of the original string, return a copy of the given string.

rstrip( )

Return a copy of the string with trailing whitespace characters removed.

split( [ separator [,maxsplit ] ] )

Return a list of substrings delimited by the given separator. If the optional maxsplit parameter is specified, its value is used to limit the maximum number of split operations performed. If maxsplit parameter is not specified, all possible split operations are performed. If the optional separator parameter is not specified, whitespace characters are used (after removing any leading and trailing whitespace characters). Listing 4.8 has a simple example of using the split() method using a single blank as a parameter.

splitlines( [keepends] )

Return a list of the lines in the string, breaking at end-of-line boundaries. If the optional keepends parameter is specified and is non-zero, then each list element will include the end-of-line delimiter.

startswith( prefix[, start[, end ] ] )

Return 1 if the string begins with the specified suffix; otherwise, return 0. The optional start and end parameters are used like slice values to indicate the portion of the string to be checked.

strip( )

Return a copy of the string with leading and trailing whitespace characters removed.

swapcase( )

Return a copy of the string with lowercase characters converted to uppercase and vice versa.

title( )

Return a copy of the string where words start with uppercase characters; all other characters are lowercase.

upper( )

Return a copy of the string where all lowercase characters are converted to uppercase.

zfill( width )

If width is greater than the given input string, return a copy of the string left padded with zeros to the specified width. Otherwise, return a copy of the input string.

String Formatting

It is difficult to precisely control the appearance of output generated using the print statement. For example, to perform an action on a group of names that have “user” as a prefix and a numeric suffix (from 0..5), you might be tempted to try something like what is shown in Listing 4.9.

Listing 4.9 “Formatted Output”—Attempt #13

image

3 Remember that when the statement-suite of a compound statement is a single simple statement, it can occur on the same line as the statement keyword.

Unfortunately, by using the comma between the “prefix” string and the number, a space is inserted between the each value (as in line 3). What if you use a plus sign to concatenate the user string with the loop control value? Let’s take a look at Listing 4.10.

Listing 4.10 “Formatted Output”—Attempt #2

image

image

What does that mean? Oh, yeah, that’s right. String concatenation is only defined for two strings, not a string and a number. Can you convert the number to a string and then concatenate? Certainly, you can use the backtick operator described in Chapter 2, “Jython Fundamentals.” Listing 4.11 shows how this might be done.

Listing 4.11 “Formatted Output”—Attempt #3

image

Is there a better way to perform string formatting? Yes, but it is much more involved than the simple display output seen previously. A string format operator exists that allows you to completely control how data should be represented. The operator uses the percent sign ("%"), and has a “format string” as the left operand and the value(s) to be displayed as the right operand.

The way to do this is to use the Jython string format operator ("%") to identify the kind of data to be displayed and how it should be displayed. When a string is followed by the percent sign, Jython processes the string and the values that follow, the result of which is a formatted string.

formatString % values

The string format operation involves the processing of the formatString, looking for format specification sequences, and using these sequences to format the associated data from the right operand. For any other text in the format string, the data is copied “as is” to the result string.

Each format specification begins and ends with a required character. The character used to indicate the start of a format specification is the percent sign ("%"), and the ending character identifies the type of data to be processed. A complete and detailed description of all the available string format options is beyond the scope of this book; however, some of the scripts will make use of this feature, so it is appropriate to provide the following information, examples, and explanations.

Section “3.6.2” of the Python Library Reference, “String Formatting Operations,” describes this topic more completely, and is available at http://docs.python.org/lib/typesseq-strings.html.

String format examples are provided in Listing 4.12 and explained in Table 4.3.

Listing 4.12 String Format Examples

image

image

Table 4.3 String Format Examples Explained

image

image

Built-in Functions

A number of built-in functions exist in Jython. They can be used without having to do anything special to make them available. One unfortunate difference between Python and Jython is that in Python, there is a special module named __builtins__ that contains all of the built-in functions identified in the following list. This is not the case with the version of Jython provided with WebSphere Application Server version 6.1. This has been corrected in version 7.0, where you are able to list these functions simply by using dir( __builtin__ ).

abs( x )

Return the absolute value of the specified numeric expression. For integers, long integers, or floating point values, the absolute value represents the positive value. If a value is negative, the sign is dropped. For complex values, the result is the square root of the sum of the squares of the values, which is sometimes referred to as the magnitude of the value. A simplistic definition is provided in Listing 4.13.

Listing 4.13 Simplistic Definition of abs()

image

callable( object )

Return 1 if the specified object appears to be callable; 0 otherwise. If this returns 1, it is still possible that an attempt to call the object could fail. But if the returned value is 0, calling the object cannot succeed.

chr( i )

Return a single character string whose ASCII value is the specified integer, which must be in the range [0..255] inclusive. For example, uppercase letters have values from [65..90], and lowercase letters have values from [91..122]. This is the inverse of ord() (defined in this section).

compile( string, filename, kind )

Compile the string into a code object. Code objects can be executed by an exec statement or evaluated by a call to eval(). If the string was read from a file, the filename parameter should specify the name of the file. Otherwise, pass some recognizable value (for example, '<string>'). The kind parameter indicates how the code contained within the string is to be compiled. The value should be one of the following:

'exec'

If the string contains a sequence of statements.

'eval'

If the string contains of a single expression.

'single'

If the string contains of a single interactive statement.

complex( real[, imag ] )

Create a complex number with the specified real and imaginary components. If the imaginary parameter is omitted, it defaults to zero. The function serves as a numeric conversion function like int(), long(), and float().

delattr( object, name )

The name parameter is a string and must be an attribute name of the specified object. The role of this function is to delete the specified object attribute. For example:

delattr(obj,'spam') is equivalent to del obj.spam

dir( [object] )

The dir function returns a sorted list of names. If no object parameter is specified, the returned list contains the names of the local objects. If an object parameter is specified, the returned list contains the attribute names of the specified object.

divmod( a, b )

The parameters must be non-complex numbers, and the result is a tuple of two numbers representing of the quotient and remainder of the expression a / b.

eval( expression[, globals[, locals] ] )

The parameters are a string and two optional dictionaries, which can be used to represent the global and local name spaces. The expression string parameter is parsed and evaluated as a Jython expression using either the specified or default globals and locals dictionaries. The return value is the result of the evaluated expression, as shown in Listing 4.14.

Listing 4.14 Sample eval() Example

image

execfile( filename[, globals[, locals ] ] )

Like the exec statement, the execfile function parses the specified input—in this case, the contents of the file named by the string. As with the eval function, the second and third parameters are optional dictionaries used to represent the global and local namespaces.4

4 Unfortunately, versions of the Application Server earlier than 6.1.0.15 appear to have a defect requiring that the filename to be executed should be specified as a literal string that does not have blanks between the parentheses and the quotation marks.

filter( function, sequence )

Build a list from those sequence elements for which the specified function returns 1. If the specified function is None, then the result contains sequence elements that are not zero, or None. filter( function, sequence ) is approximately equivalent to definition represented in Listing 4.15.

Listing 4.15 Simplistic filter() Definition

image

float( x )

Convert a noncomplex number or a string to floating point. If the parameter is numeric, Jython returns the closest approximation of this value using the available floating point precision. Otherwise, the string must contain a “well-formed” numeric value with optional leading and/or trailing whitespace characters, and Jython again returns the closest approximation of this value.

getattr( object, name[, default ] )

The name parameter must be a string and should contain the name of an attribute of the specified object. If the name is of an existing attribute of the specified object, the current value of that attribute is returned. If the specified attribute does not exist, and the default parameter is provided, its value is returned. Otherwise, an AttributeError exception is raised.

globals( )

Return a dictionary representing the current global namespace.

Warning

Do not modify the contents of this dictionary.

hasattr( object, name )

Return 1 if the string contains the name of an existing attribute of the specified object, 0 otherwise.

hash( object )

Return an integer value representing the hash value of the specified object.

hex( x )

Return a string of hexadecimal characters equivalent to the specified integer value.

id( object )

Return the (possibly long) integer representing the “identity” of the specified object. The identify of an object is guaranteed to be unique and constant for the object during its lifetime.

input( [prompt] )

The string representation of the optional prompt parameter is displayed, the user response is evaluated (using the "eval" function), and the result is returned. Therefore, this function is equivalent to eval(raw_input(prompt)). An example of using input() is provided in Listing 4.16.

Listing 4.16 Sample Use of input()

image

Warning

This function is unsafe because no checks are used to validate the user input before it is evaluated.

Using the raw_input() function allows your script to verify and validate the user specified input.

int( x[, radix ] )

Return the specified value converted to integer form. If the value parameter is a string, it must be a well-formed number and is allowed to have leading and trailing whitespace characters. The optional radix parameter specifies the conversion base to be used (and defaults to 10). The radix value can be 0 or 2 to 36 inclusive and can only be specified when the first parameter is a string. A radix value of 0 indicates that Jython should interpret the value as it does integer literals. Conversion failures cause exceptions to be raised.

isinstance( object, classinfo )

Return 1 if the object parameter is an instance of or a subclass of the specified classinfo parameter; otherwise, return 0.

issubclass( class, classinfo )

Return 1 if the class parameter is a subclass of the specified classinfo parameter; otherwise, return 0.

len( s )

Return the number of items (for example, length) of the specified object. The object could be a string, a tuple, a list, or a dictionary.

list( sequence )

Return a list built from the items in the specified sequence. Note that if the specified sequence is a list, the list and not a copy is returned.

locals( )

Return a dictionary representing the current local namespace.

Warning

Do not modify the contents of this dictionary.

long( x[, radix ] )

Return the specified value converted to long integer form. If the value parameter is a string, it must be a well-formed number and is allowed to have leading and trailing whitespace characters. The optional radix parameter specifies the conversion base to be used (and defaults to 10). The radix value can be 0 or 2 to 36 inclusive and can only be specified when the first parameter is a string. A radix value of 0 indicates that Jython should interpret the value as it does integer literals. Conversion failures cause exceptions to be raised.

map( function, sequence, ... )

Return a list containing the results of passing each sequence element to the specified function. Multiple sequences should be provided for functions requiring multiple parameters. The sequence elements are processed in parallel, passing the paired sequence items to the function for processing. Should the sequence lengths be different, the None value is supplied for the “missing” elements from the shorter sequence.

max( sequence )

Return the largest item of a non-empty sequence.

min( sequence )

Return the smallest item of a non-empty sequence.

open( filename[, mode[, bufsize ] ] )

Return a file object identified by the filename (string) parameter. If the file can’t be opened, an IOError exception is raised. The optional mode parameter is a string identifying how the file is to be opened:

'r'—Open for “read” (default)

'w'—Open for “writing

'a'—Open for “append” (i.e., writing at the end)

Note

Append 'b' to one of the mode letters shown here to indicate that the file is to be opened in “binary” mode (end-of-line characters are not respected as such). The optional bufsize parameter identifies a requested buffer size. A detailed description of this function is beyond the scope of this book. Please review the Python documentation for this information.

ord( c )

Return the ordinal value of the specified single character (which may be a Unicode character).

pow( x, y[, z ] )

Return x ** y, or ( x ** y ) % z if the optional third parameter is specified.

range( [start,] stop[, step ] )

Return a list containing a range of plain integer values generated using the specified (plain integer) parameters.5

5 It is very easy to generate a very large list using range, consider how many values are generated should you use something silly like range(2147483647). Attempts to do so, however, require a large amount of memory and could cause heap exhaustion. You might want to consider using xrange() (described and explained later in this section).

Note

If a single parameter is specified, start defaults to 0, step defaults to 1, and the value is used as stop. If two values are specified, step defaults to a value of 1. The value of step must not be zero, or a ValueError exception is raised.

raw_input( [prompt] )

Display the optional prompt string, if one exists, then read a single line of text from “standard” input, remove the tailing newline character, and return this string as the function result. An example is shown in Listing 4.17.

Listing 4.17 Sample Use of raw_input()

image

reduce( function, sequence[, initialValue ] )

Return the result of calling the specified function on the values in the specified sequence in a cumulative fashion in order to “reduce” the sequence of values to a single result. The specified function must allow two parameters and is expected to return some operation using the specified input. If the optional initialValue parameter is specified, it is used as the initial, or default, value for the processing. If the specified sequence contains a single value, reduce() returns that value. An example is shown in Listing 4.18 and explained in detail in Table 4.4.

Listing 4.18 Examples of reduce()

image

image

Table 4.4 reduce() Examples Explained

image

reload( module )

Reload a previously imported module. Unfortunately, the restrictions, limitations, and caveats related to this function are a bit beyond the scope of this book. For specific details about this function and how it should be used, look at some Python documentation, one example of which is available at http://docs.python.org/lib/built-in-funcs.html.

repr( object )

Return a string containing a displayable, or printable, representation of the specified object.

round( x[, digits ] )

Return the specified value as a floating point after rounding to the specified number of digits after the decimal point. If the digits parameter is unspecified, it defaults to 0, thus truncating any existing decimal points from the specified value. That rounding is “away from” the value 0, as seen here in Listing 4.19.

Listing 4.19 round() Example

image

setattr( object, name, value )

This is the opposite of getattr(), with the following parameters:

• The target object

• A string containing the attribute name

• The value to be bound (assigned)

str( object )

Return a string containing a displayable representation of the specified object.

type( object )

Return the type of the specified object.

unichr( i )

Return the Unicode string of characters having a Unicode code of the specified integer value.

unicode( object[, encoding [, errors ] ] )

Return the Unicode string representation of the specified object. The optional encoding parameter is a string identifying the name of the encoding code page to be used. The optional errors parameter is a string that can have one of the following values defined in Table 4.5.

Table 4.5 unicode() Error Values

image

vars( [object] )

Return a dictionary containing details about the local variables, or those of the specified object, if one is provided.

Warning

Do not modify the contents of this dictionary.

xrange( [start,] stop[, step] )

This function is very similar to range(), but instead of returning a list of all the specified values, it returns an xrange object. This special sequence type is used to obtain the same values as the corresponding list, without generating them at the time the function is called. For example, use the code shown in Listing 4.20 to see how long it takes to generate 1 billion (that is, 1E9) values, with a '.' being displayed every 10 million (1E7) values. Don’t be surprised by the time required to execute this loop. It does, however, run to completion. Trying to use range() on the same value is likely to cause an out of memory (OOM) error.

Listing 4.20 Sample Use of xrange()

image

Summary

This chapter continued our discussion of Jython, specifically related to object-oriented programming constructs (such as classes, attributes, and methods). In addition, references are provided for the built-in list, dictionary, and string methods, as well as functions that exist as part of the language. We also took a short side trip to explore the topic of string formatting.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.27.218