title: Jython - Correct way of creating class instances & executing methods from Python class
body: <p>I have a Python file which contains a class. I need to create an instance of that class and be able to call methods in that through Java.</p>
  
  <p>I came up with a solution like this:</p>
  
  <pre><code>    PythonInterpreter r = new PythonInterpreter();
      r.execfile("File.py");
  
  
      PyObject p = r.eval("Car().begin()");
      System.out.println(p.toString());
  </code></pre>
  
  <p>And the python code:</p>
  
  <pre><code>class Car(SomeExtendedClass):
  
      myvar = 5
  
      def set(self, my):
          self.myvar = my;
  
      def begin(self):
          return self.myvar
  </code></pre>
  
  <p>Now, when I execute this, it prints <code>5</code> But if I run the following code:</p>
  
  <pre><code>    PyObject p = r.eval("Car().begin()");
      System.out.println(p.toString());
  
      r.eval("Car().set(7)");
  
      p = r.eval("Car().begin()");
  
      System.out.println(p.toString());
  </code></pre>
  
  <p>It will still print <code>5</code>, instead of <code>7</code></p>
  
  <p>It looks like I did not create one instance of <code>Car</code> and it always creating a new instance instead of using the created one.</p>
  
  <p>Am I right?</p>
  
  <p><strong>Is it possible to create a new instance from a class in a Python file, and invoke/get data from methods with Java?</strong></p>
  
  <p>I have tried loading <code>PyInstance</code> using <code>eval()</code> but I get cannot cast exception from it:</p>
  
  <pre><code>return (PyInstance) this.interpreter.eval(className);
  </code></pre>