Introduction to Jython

Introduction to Jython

Chapter 2 Introduction to Jython In this chapter, we will give a short introduction to the Jython programming lan- guage. We have already pointed out that Jython is an implementation of the Python programming language, unlike CPython which is implemented in C/C++. While these implementations provide almost identical a Python-language pro- gramming environment, there are several differences. Since Jython is fully implemented in Java, it is completely integrated into the Java platform, so one can call any Java class and method using the Python-language syntax. This has some consequences for the way you would program in Jython. During the execution of Jython programs, the Jython source code is translated to Java bytecode that can run on any computer that supports the Java virtual machine. We cannot give a comprehensive overview of Jython or Python in this chapter: This chapter aims to describe a bare minimum which is necessary to understand the Jython language, and to provide the reader with sufficient information for the fol- lowing chapters describing data-analysis techniques using the jHepWork libraries. 2.1 Code Structure and Commentary As for CPython, Jython programs can be put into usual text files with the extension ‘.py’. A Jython code is a sequence of statements that can be executed normally, line-by-line, from the top to the bottom. Jython statements can also be executed interactively using the Jython shell (the tab ‘JythonShell’ of the jHepWork IDE). Comments inside Jython programs can be included using two methods: (1) To make a single-line comment, put the sharp “#” at the beginning of the line; (2) To comment out a multi-line block of a code, use a triple-quoted string. It is good idea to document each piece of the code you are writing. Documenta- tion comments are strings positioned immediately after the start of a module, class S.V. Chekanov, Scientific Data Analysis using Jython Scripting and Java, 27 Advanced Information and Knowledge Processing, DOI 10.1007/978-1-84996-287-2_3, © Springer-Verlag London Limited 2010 28 2 Introduction to Jython or function. Such comment can be accessed via the special attribute __doc__.This attribute will be considered later on when we will discuss functions and classes. Jython statements can span multiple lines. In such cases, you should add a back slash at the end of the previous line to indicate that you are continuing on the next line. 2.2 Quick Introduction to Jython Objects As for any dynamically-typed high-lavel computational language, one can use Jython as a simple calculator. Let us use the jHepWork IDE to illustrate this. Start the jHepWork and click on the “JythonShell” tab panel. You will see the Jython invitation “>>>” to type a command. Let us type the following expression: >>> 100*3/15 Press [Enter]. The prompt returns “20” as you would expect for the expression (100*3)/15. There was no any assignment in this expression, so Jython assumes that you just want to see the output. Now, try to assign this expression to some variable, say W: >>> W=100*3/15 This time, no any output will be printed, since the output of the expression from the right side is assigned directly to the variable W. Jython supports multiple assign- ments, which can be rather handy to keep the code short. Below we define three variables W1, W2 and W3, assigning them to 0 value: >>> W1=W2=W3=0 One can also use the parallel assignments using a sequence of values. In the example below we make the assignment W1=1, W2=2 and W3=3 as: >>> W1,W2,W3=1,2,3 At any step of your code, you can check which names in your program are de- fined. Use the built-in function dir() which returns a sorted list of strings >>> dir() [’W’,’W1’,’W2’,’W3’,’__doc__’, ’__name__’ ... 2.2 Quick Introduction to Jython Objects 29 (we have truncated the output in this example since the actual output is rather long). So, Jython knows about all our defined variables including that defined using the character W. You will see more variables in this printed list which are predefined by jHepWork. One can print out variables with the print() method as: >>> print W1 1 One can also append a comment in front: >>> print ‘The output =’,W1 The output = 1 You may notice that there is a comma in front the variable W1. This is because ‘The output’ is a string, while ‘W1’ is an integer value, so their types are distinct and must be separated in the print statement. How do we know the variable types? For this we can use the type() method which determines the object type: >>> type(W1) <type ’int’> The output tells that this variable holds an integer value (the type “int”). Let us continue with this example by introducing another variable, ‘S’ and by assigning a text message to it. The type of this variable is “str” (string). >>> S=’The output =’ >>> type (S) <type ’str’> So, the types of the variables ’W1’ and S are different. This illustrates the fact that Jython, as any high-level language, determines types based on assigned values during execution, i.e. a variable may hold a binding to any kind of object. This feature is very powerful and the most useful for scripting: now we do not need to worry about defining variable types before making assignments to a variable. Clearly, this significantly simplifies program development. Yet, the mechanics behind such useful feature is not so simple: the price to pay for such dynamical features is that all variables, even such simple as ‘W1’ and ‘S’ de- fined before, are objects. Thus, they are more complicated than simple types in other programming languages, like C/C++ or FORTRAN. The price to pay is slower ex- ecution and larger memory consumption. On the other hand, this also means that you can do a lot using such feature! It should also be noted that some people use 30 2 Introduction to Jython the word “value” when they talk about simple types, such as numbers and strings. This is because these objects cannot be changed after creation, i.e. they are im- mutable. First, let us find out what can we do with the object ‘W1’. We know that it holds the value 10 (and can hold any value). To find out what can be done with any objects in the JythonShell window is rather simple: Type ‘W1’ followed by a dot and press the [Space] key by holding down [Ctrl]: >>> W1. [Ctrl]-[Space] You will see a list of methods attributed to this object. They usually start as __method__, where ’method’ is some attribute. For example, you will see the method like __str__, which transforms an object of type integer to a string. So, try this >>> SW=str(W1); type(SW) <type ’str’> Here we put two Jython statements on one line separated by a semi-column. This, probably, is not very popular way for programming in Jython, but we use it to il- lustrate that one can this syntax is also possible. In some cases, however, a program readability can significantly benefit from this style if a code contains many similar and short statements, such as a1=1; a2=2. In this case, the statements have cer- tain similarity and it is better to keep them in one single logical unit. In addition, we will use this style in several examples to make our code snippets short. The last expression in the above line does not have “=”, so Jython assumes that what you really want is to redirect the output to the interactive prompt. The method type() tells that “SW” is a string. As before, you may again look at the methods of this object as: >>> SW. [Ctrl]-[Space] This displays a list of the methods attributed to this object. One can select a neces- sary method and insert it right after the dot. In addition to the JythonShell help system, one can discover the attributes of each Jython object using the native Jython method dir(): >>> dir(SW) In the following sections we will discuss other methods useful to discover at- tributes of Java objects. 2.2 Quick Introduction to Jython Objects 31 2.2.1 Numbers as Objects Numbers in Jython are immutable objects called values, rather than simple types as in other programming languages (C/C++, Fortran or Java). There are two main types: integers (no fractional part) and floats (with fractional part). Integers can be represented by long values if they are followed by the symbol ‘L’. Try this: >>> Long=20L <type ’long’> The only limit in the representation of the long numbers is the memory of Java virtual machine. Let us take a look again at the methods of a real number, say “20.2” (without any assignment to a variable). >> 20.2. [Ctrl]-[Space] or, better, you can print them using the method “dir()” >>> dir(20.2) Again, since there is no any assignment, Jython just prints the output of the dir() method directly to the same prompt. Why they are needed and what you can do with them? Some of them are rather obvious and shown in Table 2.1. Table 2.1 A short overview of the Jython operators for values Jython operators for values abs(x) __abs__ absolute value pow(x, y) or y**x __pow__ raise x to the power y −x,+x __neg__, __pos__ negative or positive +, - __radd__, __rsub__ add or subtract ∗, / __rmul__, __rdiv__ add or subtract x<y, x>y __com__ less or larger. Returns 0 (false) or 1 (true) cmp(x, y) __com__ compare numbers.

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    58 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us