Android studio calls Python class

The process of calling a Python class is basically similar to the process of calling a Python module, except that you need to use the class method to call the method.

 

Suppose there is a Python class file "test.py", which defines a class named "Calculator", which contains an addition method add() and a multiplication method multiply(). We can call this Python class in Android Studio with the following Java code:

 

```java

import org.kivy.android.PythonInterpreter;

import org.python.core.PyObject;

import org.python.core.PyType;

 

// ...

 

PythonInterpreter interpreter = new PythonInterpreter();

interpreter.execfile("test.py");

PyType pyType = (PyType) interpreter.get("Calculator").__getattr__("__class__").__findattr__("__class__");

PyObject pyObject = pyType.__call__();

PyObject addResult = pyObject.invoke("add", 1, 2);

PyObject multiplyResult = pyObject.invoke("multiply", 3, 4);

 

int addValue = addResult.asInt();

int multiplyValue = multiplyResult.asInt();

 

Log.d("Python", "Add result: " + addValue);

Log.d("Python", "Multiply result: " + multiplyValue);

```

 

In this Java code example, we first create a PythonInterpreter object and use the execfile() method to load the test.py file. Then use the get() method to get the Calculator class object, and use the \_\_getattr\_\_() and \_\_findattr\_\_() methods to get the type (PyType) object of the class. Then use the \_\_call\_\_() method to call the constructor of this class, create an instance of the class (pyObject), and then call the methods in the class directly through pyObject.

 

Use the invoke() method to call the add() and multiply() methods and store the results in the addResult and multiplyResult variables. Finally these results are converted to Java types (here converted to integers) and printed out.

 

It should be noted that when calling a Python class, a class instance object needs to be created, so the \_\_call\_\_() method needs to be used to call the constructor of the class to create the instance. In addition, you also need to pay attention to the need to pass the correct number and types of parameters when calling Python methods.

Guess you like

Origin blog.csdn.net/weixin_59246157/article/details/130845224