[Tutor] Differnce between java and python

Alan Gauld alan.gauld at freenet.co.uk
Wed Dec 21 22:21:50 CET 2005


>>Python is more forgiving
> 
> Could you elaborate on this feature?

Python allows you to do things, without complaining, that Java just 
won't allow.

As one example: you create a Java module M containing a class C 
with a method F that throws exception E. Now to use that in your 
code, say called by function g() you must import the module and 
also ensure that the function g() is either defined to throw E 
- or to handle the exception E. The compiler complains otherwise.

In Python you simply import the module and call the function. If the 
exeception is thrown it will generate a stack trace exactly as if you 
had thrown it inside your code. Of course you might want to handle 
it locally, but you don't have to be explicit about it.

Another example is that Python supports "Duck Typing", that is 
its type checking  is protocol based. So if I declare a function 

def f(aNumber): ...

I can pass in anything that acts like a number, provided it can respond 
to the subset of numeric operations that I use I can pass in anything.

If I nor define a Java funtion/method

void f(int n){....}

I can only pass in an integer or something that can be typecast as 
an integer. Very often that's far too strict a limitation.

Now the strictness is there for a reason and it encourages good design, 
but it does require much more thought up front about exactly what will 
be passed where and which exceptions will be thrown where etc. If you 
are just learning, or want to get a quick job done then Java's approach 
is frustrating rather than helpful.

That's what I mean by Pyython being more forgiving, or tolerant, 
than Java.

HTH,

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld




More information about the Tutor mailing list