从 Java 调用 Python 类实例函数

发布于 01-10 17:45 字数 918 浏览 3 评论 0原文

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. 一旦检索到实例,如何直接调用类实例函数?
  2. 如果 1 不可能,我可以从实例中检索表示该函数的 PyObject 并调用它吗?如果是,怎么办?是否会在从中检索它的实例上调用它?
  3. 如果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 interpreter
PyObject 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:

  1. How can I directly call a class instance function once I've retrieved the instance?
  2. 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?
  3. If neither 1 nor 2, what's the way to do this? Is a module-level "wrapper" function like TestFunc() the only way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文