我有一个扩展PyObject
的Java类,其中包含我想要用于查找的Map<String,Object>
,我认为我在Jython中可以免费获得dict
行为。相反,我收到错误TypeError:
myclassname object is unsubscriptable
。
看起来我必须至少实现PyObject.__finditem__()
方法(见第654-670行):
/**
* Very similar to the standard Python __getitem__ method.
* Instead of throwing a KeyError if the item isn't found,
* this just returns null.
*
* Classes that wish to implement __getitem__ should
* override this method instead (with the appropriate
* semantics.
*
* @param key the key to lookup in this container
*
* @return the value corresponding to key or null if key is not found
**/
public PyObject __finditem__(PyObject key) {
throw Py.TypeError(String.format("'%.200s' object is unsubscriptable",
getType().fastGetName()));
}
我该怎么做?是否有一个检查PyObject
是否为String
的示例?如果密钥不是字符串会发生什么?
我是否还必须覆盖__contains__
?
(这与exposing a Java Map<> in Jython so that its keys are available with Python "dot" operator (attribute access)相似,但有一个相对简单的解决方案。)