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
- Indentation determines blocks, not braces. In a way, the colon
can be seen as an opening brace.
- One statement per line
- If you want one statement to span multiple lines, there must be
an opening parenthesis somewhere (or you could escape the return with a
backslash)
- If you want several statements per line, you can append 1
single statement after a colon (handy for if-statemements)
- Additionally, there is a core syntax that is not usually used,
but
available, that allows one to
- use braces for blocks
- semicolons for command separation
- Use for hard cases only
Small differences with Java:
- if-statement does not need parentheses
- null is None in Python, true is True, false is False
- Komments are per-line only: //
in Java is # in Python
- There is no decrement operator, use: a-=1
- There are no char literals. Therefore: you can use either
single or double
quotes for strings
- Strings can be destructively changed
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:
- Qualified:
import javax.swing.
Now you have to always qualify your class names: javax.swing.JButton("hi")
- Unqualified single:
from
javax.swing import JButton.
Leads to unqualified class names: JButton("hi")
- Unqualified all:
from javax.swing import *.
Every class in that package can be used unqualified: JLabel("hello")
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:
- dictionary literals
- higher-order functions (functions as actual parameters for
functions)
- iterators (similar to Java)
- several quick ways to transform and generate lists (some of them
borrowed from function programming languages)
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