0

以下是我的java代码:

public void testPySet() {
    final PythonInterpreter interpreter = new PythonInterpreter();
    final String userCode = "def test(x):\n\tprint(x)\n\tx.add(\"d\")\n\treturn x";
    interpreter.exec(userCode);
    final PyObject method = interpreter.get("test");
    final PySet set = new PySet(PyString.TYPE);
    set.add("a");
    set.add("b");
    set.add("c");
    final PyObject result = method.__call__(set);
    System.out.println(result);
}

当我运行它时,它会抛出一条错误消息:

Traceback (most recent call last):
  File "<string>", line 3, in test
AttributeError: 'str' object has no attribute 'add'

如果我删除x.add(\"d\"),那么它将成功运行。

PySet对象被识别为对象是非常奇怪的str

有谁碰巧知道为什么?

4

1 回答 1

0

这个答案来自邮件列表上的 Jim Baker :

问题出在一线

final PySet set = new PySet(PyString.TYPE);

我认为您正在尝试将其用作 PySet set = new PySet(),但实际上这意味着 Python 代码中生成的对象的类型应该是 PyString。这正是您所观察到的!

(为什么会这样?我们在 Jython 中有两个对象模型:Python 和 Java,我们必须在运行时结合支持。这样做可能有点棘手!)

解决方法很简单:把初始化改成

final PySet set = new PySet()
于 2015-06-17T17:09:15.343 回答