[Tutor] Slightly OT - Python/Java

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Tue Jan 11 01:29:51 CET 2005



On Tue, 11 Jan 2005, Liam Clarke wrote:

> > > (Why can't a non-static method comparison be called from a static
> > > reference? What does that mean anyway?
> >
> >         Er... What was your code like? (before and after correcting
> > the error)


Hi Liam,

It's actually easier to see the reason if we do a comparative "buggy code"
display between Java and Python.  *grin*



Here's an instance of what I think the error might be:

/*** Java pseudocode: won't compile. ***/
public class TestStatic {
    public static void doSomething() {
        System.out.println("square(42) is " + square(42));
    }
    public int square(int x) {
        return x * x;
    }
}
/******/


And here's a loose translation of the buggy Java code into buggy Python
code.  [meta: I'm not using Python's staticmethod() stuff yet; maybe
someone else can show that approach too?]


### Python pseudocode: won't run right ###
def doSomething():
    print "square(42) is", TestStatic.square(42)

class TestStatic:
    def square(self, x):
        return x * x
######


The bug should be more obvious now: it's a simple parameter passing
problem.


In Python, the 'self' parameter is explicitely defined and stated as part
of the parameter list of any method.  square() is actually a method that
must take in an instance.  Easy to see, since square takes in two
parameters, but we are only passing one.

In Java, the bug is harder to see, because the passing of 'this' (Java's
equivalent of 'self') is all being done implicitely.  In Java, static
functions aren't bound to any particular instance, and since there's no
'this', we get that error about how "static member functions can't call
nonstatic method functions."



That being said, it's perfectly possible to do this:

/******/
public class TestStatic {
    public static void doSomething() {
        TestStatic app = new TestStatic();
        System.out.println("square(42) is " + app.square(42));
    }

    public int square(int x) {
        return x * x;
    }
}
/******/


with its Python equivalent:

######
def doSomething():
    app = TestStatic()
    print "square(42) is", app.square(42)

class TestStatic:
    def square(self, x):
        return x * x
######


The explicitness of 'self' in Python really shines in examples like this.



> >         Oh Ghost. You didn't actually write a Java program using a
> >         regular text editor, did you?
> >         And of course, it's free (and written in Java). http://www.eclipse.org
> >
>
> *sigh* I have no net at home at moment, which is very frustrating when I
> want to d/l documentation & editors. For the mo, it's all Notepad. Ick.


Don't inflict that kind of pain on yourself.  Ask someone to burn a CD of
Eclipse for you or something: just don't use bad tools like Notepad!
*grin*


Best of wishes to you!



More information about the Tutor mailing list