从 Java 调用 Python 类实例函数
Python 代码
class TestClass(object):
def TestFunc(self):
print("TestFunc!")
_test_class = TestClass()
def TestFunc():
_test_class.TestFunc()
Java 代码
public static void Main(String[] args){
PythonInterpreter pi = new PythonInterpreter();
// Execute python code here using pi.execfile() or pi.exec()
PyObject testClass = pi.get("_test_class");
// testClass is successfully obtained
// <- Answer goes here
}
那么,这是我的问题。可以吗?如果可以,我如何在从 Python 解释器检索到的 TestClass 实例上调用 TestFunc() ?
我可以轻松地从解释器获取非类 TestFunc 函数 PyObject func = pi.get("TestFunc")
,然后调用它“func.__ call __()”,这是一种解决方案,但我更喜欢直接在实例上调用函数。
所以,问题是:
- 一旦检索到实例,如何直接调用类实例函数?
- 如果 1 不可能,我可以从实例中检索表示该函数的 PyObject 并调用它吗?如果是,怎么办?是否会在从中检索它的实例上调用它?
- 如果1和2都不是,那么该怎么做呢?像 TestFunc() 这样的模块级“包装”函数是唯一的方法吗?
Python code
class TestClass(object):
def TestFunc(self):
print("TestFunc!")
_test_class = TestClass()
def TestFunc():
_test_class.TestFunc()
Java code
public static void Main(String[] args){
PythonInterpreter pi = new PythonInterpreter();
// Execute python code here using pi.execfile() or pi.exec()
PyObject testClass = pi.get("_test_class");
// testClass is successfully obtained
// <- Answer goes here
}
So, here's my question. Can and, if so, how do I call TestFunc() on the TestClass instance I retrieved from the Python interpreter?
I can easily get the non-class TestFunc function from the interpreterPyObject func = pi.get("TestFunc")
and then call it 'func.__ call __()' so that's one solution but I'd prefer to call a function directly on the instance.
So, questions are:
- How can I directly call a class instance function once I've retrieved the instance?
- If 1 isn't possible, can I retrieve a PyObject representing the function from the instance and call that? If yes, how? Will it be called on the instance it was retrieved from?
- If neither 1 nor 2, what's the way to do this? Is a module-level "wrapper" function like TestFunc() the only way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论