【问题标题】:isinstance in JythonJython 中的实例
【发布时间】:2015-08-26 17:57:26
【问题描述】:

在 CPython 中,您可以使用 isinstance(something, list) 来检查某个东西是否是 list

但是,同样的代码在 Jython 中不起作用。在 Jython 中,它会引发此异常:TypeError: isinstance(): 2nd arg is not a class

【问题讨论】:

  • 您使用的是哪个版本的 Jython?我刚刚尝试了 2.7b2 和 2.7b4,它们按预期工作。
  • @DavidCharles:我使用的是 WAS 8.5 附带的版本,它已经过时了。 2.1 版。 list 在您的版本中是 class 吗?我想知道list 在 Python 2.1 中是否是 function。无论哪种方式,我都在 Python 2.6 和 Jython 2.1 下运行这些脚本,所以我需要编写它们以便它们在两者中运行。
  • 回答你的问题:在 jython2.7b2 上,list.__class__ 打印 <type 'type'>,这正是 python2.7.6 所说的。

标签: list class jython isinstance


【解决方案1】:

在 Jython 中,listfunction,而不是 class。您可以通过运行:list.__class__ 来找到它,它将打印 <jclass org.python.core.BuiltinFunctions at ...>,而 Python 将在相同的代码下打印出 <type 'list'>

我找到了两种方法来完成这项工作。

  1. 使用isinstance(something, [].__class__)
  2. 如果您在 Jython 中运行 [].__class__,它将打印出 <jclass org.python.core.PyList at ...>。所以你可以先import org 然后isinstance(something, org.python.core.PyList)

这两个选项看起来都不是很好。第二个可能更容易理解,但缺点是只能在 Jython 上工作,而第一个在两个运行时上都一样好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-02
    相关资源
    最近更新 更多