JPython and subclassing from an abstract class

D-Man dsh8290 at rit.edu
Wed May 23 09:34:07 EDT 2001


On Wed, May 23, 2001 at 03:01:27PM +0200, Pieter Laeremans wrote:

| public class Rational {
| 
| public Rational(numerator, denominator){}
| 
| public long getDenominator(){}
| public longgetNumerator(){}
| 
| }
| 
| public abstract class Constraint {
| 
| public abstract String getDescription();
| public boolean satisifies(Rational rational);
| 
| }

What java package are these in?

| I want to subclass this class in python but it doesn't work.
| I've tried:
| 
| class testConstraint(Constraint):
                       ^^^^^^^^^^

This is correct, but does the name "Constraint" exist in the current
namespace?  If so, does it refer to the java class above?

| 	define getDescription(self):
| 		return "test"
| 	define satisfies(self, rational):
| 		return rational.getDenominator()
| 
| This didn't  work!
| I could crate an instance
| t = testConstraint

Actually, you didn't create an instance here, you just created an
alias for the class name (class are first-class object in Python,
unlike Java, C++, and Eiffel).  Instead you need :

t = testConstraint()

| but when i tried
| r = Rational(2,1)
| t.satisfies(r)
| 
| I got an error message.

What error message?!  If you provide the error message then I won't
have to guess at what went wrong -- the interpreter always tells you.

Assuming the java class is in the default unamed package you need to
have

import Constraint

above the definition of the python class.  If you already have that,
the problem might be the incorrect instantiation of the class (as
noted above).

Another point: when you post code in an email be sure to include all
of the relevant code exactly as you tried it.  Sometimes subtle
differences in what you actually have and what is posted makes all the
difference in the world.

I also notice that the Rational class retuns a 'long' from
getDenominator.  In your testConstraint class you are supposed to
return a boolean from the satisfies method, but you return the result
from getDenominator.  I am not sure exactly what type of object is
returned because Jython does a bunch of automatic type conversion to
try and unite the Python and Java models.  (I think that the java
'long' would be converted to a python long (or int) which gets
converted to a java 'boolean' when java expects a boolean)

Also, what version of JPython are you using?  If it really is JPython
then it is obsolete -- the project has been renamed Jython and Jython
has a couple of new releases.

I hope this brings you closer to solving your problem, and if you post
some additional information I will be glad to provide some more help.

-D





More information about the Python-list mailing list