An Introduction to Jython

Source: Internet
Author: User

An Introduction to Jython

 

By Mike

 

Table of contents

Introduction
Java objects and methods in Jython
Jython import statements
Event handling
Overloaded Java Methods
Classes in Jython
Public vs. Private Variables
Subclassing and inheritance
Simulating interfaces with multiple inheritance
Notes on static final classes
Conclusion

 

Jython is a version of Python written in Java and designed to run under the JVM. because of this, it integrates closely with Java, and allows Jython programs access to all of the Java libraries. there are several reasons that Java programmers might be interested in learning Jython:

 

It provides an alternative to JavaScript for interacting with Java, and is in every ways more powerful than Javascript. Most wowould also agree it is much easier to use than JavaScript.

It is very easy to embed the Jython interpretor as a scripting or application control language in your Java applications.

It allows more rapid prototyping, and/or "proof of concept" applications than is possible in Java.

With this very short and brief introduction, Lets jump right into some code. In the spirit of programming books, we will start with the very simple "Hello world! "Program as it wocould be written in Jython:

Print "Hello, world! "

Of course, the first thing you are likely to notice about this complete Jython program, is how simple it is. unlike regular Java, Jython does not force us to use Object Oriented Programming if we don't want. we don't have to enclose our program in a class, or even in a function. in reality, this program is enclosed in a class and also in a function to satisfy the requirements of Java. however, Jython does that behind the scenes so we don't have to worry about it. now lets look at a slightly more advanced example:

 

File = open ("test.txt", "R ")

For line in file. readlines ():
Print line

File. Close ()

 

There are several significant aspects of Jython to point out here. the first is that it is very loosely typed. we don't have to declare the type of the variable that holds the file object before we can assign to it.

 

The second is that it demonstrates the use of Jython's for loop, which is different than the for loop you are used to in Java. in Jython, A for loop performs the body of the loop once for each item in a set of items it is given, which is usually a list (array) or tuple. (a tuple is basically an immutable array .) in this case, we have told Jython to place all of the lines in the text file into a list of strings, and then perform the body of the loop once for each string in the list, which of course, simply prints each line of the text file out to the console. this combination of opening the file and iterating over its contents shows how easy and quick it is to create and use objects for common tasks in Jython.

 

If you want a more traditional for loop in Jython, you can use the range () function, which will give the for loop a range of numbers to iterate over. For example:

 

For I in range (10 ):

Will repeat the loop from 0 to 9, with I taking on the values of 0 through 9 with each repetition.

The final thing to note here is that in Jython, whitespace is significant. however, before you panic and have flashbacks of FORTRAN, note that Jython's use of whitespace makes a lot of sense. in the example, the body of the For Loop is delimited by the start and end of indentation. jython code blocks are always delimited by indentation rather than braces. so basically, just indent code as you normally wocould, and Jython's use of whitespace being significant will seem very natural.

 

Java objects and methods in Jython

Of course, as I mentioned at the start of this article, one of Jython's biggest strengths is its ability to use Java libraries. So lets start with a simple example using swing components:

 

From javax. Swing import *

Frame = jframe ("Hello Jython ")
Label = jlabel ("Hello Jython! ", Jlabel. Center)
Frame. Add (Label)
Frame. setdefaclocloseoperation (jframe. exit_on_close)
Frame. setsize (300,300)
Frame. Show ()

 

Most of this code will be immediately familiar to Java programmers. the only difference being the syntax differences of not using the new keyword, and of not requiring terminating semicolons. once again, we also did not have to enclose our program in a class or main method.

 

Jython import statements

Jython import statements do require a bit more discussion here though since there are several ways we can do it. in the above example, we used the from syntax to import everything from javax. swing using the * wildcard, and we did it in such a way that we can use unqualified names. this is often considered bad style since it pollutes the global namespace. another way we can do this is to import only what we need. for example, we cocould have used the following import statement in the above example:

 

From javax. Swing import jframe, jlabel

Here we can still use the unqualified names when we want to instantiate these classes, but we have also greatly discounted the risk of a name collision by only importing what we needed.

 

Another way we can import into Jython is by using import without from. For example:

 

Import javax. Swing

If we do it this way, we have to use the qualified names. For example, we wowould need to type:

 

Label = javax. Swing. jlabel ("Hello, Jython", javax. Swing. jlabel. Center)

Although it is more typing, we have avoided polluting the global namespace.

 

Event handling

Basic event handling in Jython is also significantly easier than in Java. The following example replaces the jlabel with a jbutton to show how easy it is:

 

From javax. Swing import *

Def Hello (event ):
Print "Hello, world! "

Frame = jframe ("Hello Jython ")

Button = jbutton ("hello", actionreceivmed = Hello)
Frame. Add (button)

Frame. setdefaclocloseoperation (jframe. exit_on_close)
Frame. setsize (300,300)
Frame. Show ()

 

Once again, this is simple enough that it doesn't require much explanation. we have simply created a function, and bound it to the button using the action=med parameter. and we did it without having to create any listeners or anonymous inner classes. jython handles the messy details of creating listeners and such for us. our function compute es one argument when it is called that contains a long list of properties regarding the event. if you want to see this list of properties, simply add "Print event" to the hello function.

 

There is one problem that becomes apparent here. we do not have a way to pass any arguments to the event handler. we can't simply do something like "hello (5 )". if you try, the AWT event queue will throw a typeerror exception. so what can we do if we need to pass arguments to the event handler? We can use a lambda. for those of you with some experience in a functional programming language such as LISP, you may remember that a lambda is an anonymous function. (The name is taken from the same term in calculus, which also means an anonymous function .) what we need to do here, is wrap the real event handler call in a Lambda so that the AWT event queue only gets one argument. it looks like this:

 

Button = jbutton ("hello", actionreceivmed = Lambda X, Param = 5: Hello (PARAM ))

 

This syntax may look a bit strange at first, but what we 've got done is pretty simple. the Lambda has two parameters: X being the hello function, And Param being the value 5. when action=med is called, the lambda returns an anonymous function that invokes hello with the argument of 5. however, since the AWT event queue only got a single argument (the anonymous function returned by the lambda), it is happy and doesn't complain about a typeerror anymore. if this still seems a little confusing, consider that in Jython, instead of using the normal def funcname () syntax, We cocould, if we wanted to, define a function like this:

 

Adder = Lambda X, Y: x + y

It's unorthodox, but it works. adder is now a reference to an anonymous function that takes two arguments and adds them together. we wowould call it like any other function, adder (5, 5), for example.

As an interesting side note, our adder function is automatically polymorphic because of the overloaded behavior of Jython's + operator. All three of the following adder CALS are legal and will have the expected behavior:

 

Adder (5, 5)
Adder (5.75, 3.15)
Adder ("string1", "string2 ")

 

Keep this in mind as you write Jython functions and methods. Most of the ones you write will automatically be polymorphic because most of the Jython statements you will build them from are polymorphic in nature.

 

Overloaded Java Methods

One other issue regarding calling Java methods before we move on. Because Jython is loosely typed, We can sometimes run into problems when calling overloaded Java methods. How do we determine which method to call? In this case, we can specifically tell Jython how it shoshould treat the value we are using by passing a Java type. for example, if we have an overloaded Java method that can take either a float or a double as a parameter, we can tell Jython how to treat the passed value with something like the following:

 

From Java. Lang import float, double

Foo (float (5.5 ))
Foo (double (5.5 ))

 

Basically, you can think of it is casting the value to the correct type so that Jython knows which version of the overloaded Java method to call.

 

Classes in Jython

Now that we have seen the basics of using Jython, lets look into Jython's support for object oriented programming. Creating a class in Jython is quite simple. Lets look at an example.

 

Class Hello:
Def _ init _ (self, name = "John Doe "):
Self. Name = Name

Def greeting (Self ):
Print "Hello, % s" % self. Name

Jane = Hello ("Jane Doe ")
Joe = Hello ("Joe ")
Default = Hello ()

Jane. Greeting ()
Joe. Greeting ()
Default. Greeting ()

 

As you 've probably figured out, that _ init _ method is the constructor, And we can pass it default arguments for any arguments the user does not supply, as with the name argument. note also that we can supply named parameters when we instantiate a class or call a method. for example, we cocould write:

 

Jane = Hello (name = "Jane Doe ")

If we do things this way, it doesn't matter what order we supply the arguments in.

 

So what is that self term? It is a reference to the current instance of the class. in other words, it is the equivalent of the Java this reference. calling it self is just a Jython convention. you can use any name you want. you cocould call it this if you want. unlike Java, Jython requires us to prefix any instance variable with self. failing to provide the self prefix will usually result in an exception being thrown. note also that when creating a bound method, the first parameter to the method is always self. also, if you wish to call a bound method from within the class that it is a member of, you must prefix it with self. so for example, if we want to call our greeting () method from within the class, we wocould write:

 

Self. Greeting ()

So what do we do if we want a static variable? The following example modifies the above example slightly and uses a static variable:

Class Hello:
Name = ""

Def _ init _ (self, name = "John Doe "):
Hello. Name = Name

Def greeting (Self ):
Print "Hello, % s" % Hello. Name

Jane = Hello ("Jane Doe ")
Joe = Hello ("Joe ")
Default = Hello ()

Jane. Greeting ()
Joe. Greeting ()
Default. Greeting ()

 

We simply prefix the variable with the class name instead of with self. in the above example, all of the greeting () method callwill print John Doe because that is the last name that was assigned when the class was instantiated, thus giving us the expected behavior for a static variable.

 

Public vs. Private Variables

In Jython, variables and class methods can either be public or private. there is no "protected" level of visibility as there is in Java. the variables and methods in our previous examples were public. if we want to make them private, We Can prefix them with a double underscore. for example, the following Variable wocould be private:

 

Self. _ name = Name

 

Subclassing and inheritance

Now lets take a look at a subclassing and inheritance example in Jython. Admittedly, this example is very contrived, But it points out the basic concepts and features of subclassing in Jython.

 

Class Hello:
Def _ init _ (Self ):
Self. Hello = "hello"

Class goodbye:
Def _ init _ (Self ):
Self. Goodbye = "Goodbye"

Class greeter (hello, goodbye ):
Def _ init _ (Self ):
Hello. _ init _ (Self)
Goodbye. _ init _ (Self)

Def printer (Self ):
Print self. Hello
Print self. Goodbye

X = greeter ()
X. printer ()

 

Uh oh... you guessed right. yes, Jython allows multiple inheritance, as we demonstrate in the above example. the magic that Jython does behind the scenes to allow us to do this is beyond the scope of this article, and of course, no one says you have to use multiple inheritance. however, this example demonstrates how to use inheritance in Jython classes. our greeter class inherits from both hello, and goodbye. as you probably guessed, our greeter constructor callboth superclass constructors using the classname. _ init _ syntax. we use this same classname. method syntax for any method we want to call in the superclass.

 

Now that we have shown that Jython does allow us to use multiple inheritance, lets see an example of how Java programmers might want to use it.

 

Simulating interfaces with multiple inheritance

The following example shows how we can simulate an interface using multiple inheritance in Jython:

 

Class myinterface:
Def _ init _ (Self ):
If not hasattr (self, "mymethod "):
Raise attributeerror ("myclass must implement mymethod ")

Class myclass (myinterface ):
Def _ init _ (Self ):
Myinterface. _ init _ (Self)

In this example, we 've introduced a few new concepts. The first is the hasattr Jython built in function.

 

Here we have used it to simulate an interface by using multiple inheritance. if myclass does not contain the method mymethod, then myclass will throw an attributeerror exception when we try to instantiate it because of the inherited behavior from the myinterface constructor. this example also shows the basics of throwing our own limits tions in Jython.

 

So how is this interface simulation useful? Jython has another built in method called isinstance that we can use to determine whether a given object is an instance of any given class. although type checking is generally considered bad in Jython since we wocould prefer our objects to be as polymorphic as possible because of the loose typing, sometimes it is necessary. using the hasattr and isinstance built in functions, we can set up an interface style relationship that requires a class to contain a certain method or methods, and allows us to treat that class as an object of the interface type provided it has those methods. if it does not have those methods, we will get an attributeerror exception when we try to instantiate it.

 

Notes on static final classes

One final note. in Java, you are used to the idea of static classes to create helper functions, or utility methods. although it is possible to create static classes in Jython, it shoshould almost never be done and is almost always unnecessary. because Jython does not require us to use Object Oriented Programming, utility "classes" can simply be implemented as modules instead. here is an example:

 

# Comment: mymath "utility" Class

Def square (x ):
Return x * x

Def cube (x ):
Return x * x

Later, if we want to call these utility functions from another module, we can simply do it like this:

Import mymath

X = mymath. Square (5)
Y = mymath. cube (5)

As you can see, classes are not necessary here for these utility functions, and Python's Import Statement allows us to import the functions in their own namespace so that we do not pollute the global namespace despite the fact that we are not using a class.

 

Conclusion

This article has only provided a simple introduction to Jython, and how it can be a powerful tool in a Java programmer's arsenal. for those who want to learn more, you can use any normal Python tutorial to learn Jython. the Jython specific aspects such as using Java libraries will come naturally since it is almost identical to using those libraries in Java itself.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.