Homepage, Blog > Articles >

Python for Java Programmers


Jython is a complete Python interpreter that runs on the Java Virtual Machine and can access all Java data at runtime: classes, objects etc. Therefore, you can easily use Python to script you Java applications. For that reason, here is a short summary of what you need to know about Python as a Java programmer.

Quick Start

% python   # interactive python interpreter, quit via ctrl-D
>>> help() # enter interactive help mode

>>> help("str") # help for string class
>>> dir(str) # list contents of any Python entity

Syntax

Small differences with Java:
Other differences:
>>> a = "bla"
>>> b = "b" + "la"
>>> a == b # Java: .equals
True
>>> a is b # Java: ==
False
>>> (3 != 5) or not (7 == 8) and True # Java: || && etc.
True
>>> a=5
>>> a-=1 # there is no decrement operator --
>>> a
4

Loops

>>> for i in ["a", "b", "c"]:
... print i
...
a
b
c
>>> for i in range(1,5):
... print i
...
1
2
3
4

Built-In Functions

repr and str both return strings:
>>> str(334)
'334'
>>> repr('hallo')
"'hallo'"
>>> str('hallo')
'hallo'
>>> repr(334)
'334'
>>> len([3,4,5])
3

Classes

Watch out: this is an implicit parameter in Java, but is made explicit as the first parameter self in Python. Also: It is very bewildering for Java programmers, but in Python the only way to create an instance variable is by setting an attribute (for example, in the constructor)
>>> class MyClass:
... classVar = 555
... def __init__(self, arg): # constructor
... self.instanceVar = arg
...
>>> a = MyClass("hi") # Python does not have the 'new' keyword
>>> a.instanceVar
'hi'
>>> a.newInstanceVar = "externally created"
>>> a.newInstanceVar
'externally created'.

Importing

There are three ways of importing classes:

Neat Things That Java Can't Do

There are several ways to call a method:
>>> class A:
... def myMethod(self, arg):
... print "Look:", arg
...
>>> a = A()
>>> b = A.myMethod # a "method pointer"
>>> b(a, "world")
Look: world
>>> A.myMethod(a, "lala")
Look: lala
Percentage operator: handy for filling out strings:
>>> myName = "Mr. Boombastic"
>>> "My name is: %s" % myName
'My name is: Mr. Boombastic'
>>> 'My name is: %(myKey)s' % { "myKey": "Roger Rabit" }
'My name is: Roger Rabit'
>>> 'Still my name: %(myName)s' % locals() # lists all currently active local vars
'Still my name: Mr. Boombastic'
String literals:
>>> r'\n'      # raw strings
'\\n'
>>> """spans # multi-line string literals
... several
... lines
... """
'spans\nseveral\nlines\n'

And Much More...

Consult the Python tutorial:
Resources:

Wanted: Your Feedback

This document is never going to turn into a full-fledged Python tutorial, but if there is anything that has really puzzled you in Python as a Java programmer, please let me know and I'll add it to this page.


Axel Rauschmayer
Last modified: Sat Aug 28 14:55:57 CEST 2004