Search code examples
androidchaquopy

Chaquopy not initializing class


When using chaquopy for android, calling a module from java does not run the __init__ method.

PyObject utilModule = py.getModule("utils.Utils").get("Utils");

Creates an object reference to python without the constructor. Is there any way to do this without an additional "init" function and calling that after creation?


Solution

  • Assuming utils.Utils is a module, and Utils is a class within that module, your code is just getting a reference to that class. If you want to actually instantiate the class, you can either do this:

    PyObject utilObj = py.getModule("utils.Utils").callAttr("Utils");
    

    or this:

    PyObject utilClass = py.getModule("utils.Utils").get("Utils");
    PyObject utilObj = utilClass.call();
    

    If you want to pass constructor parameters, just add them at the end of the parameter list of callAttr or call.

    See the ZipFile example in the documentation.