gpt4 book ai didi

python - Cython - 检查对象类型

转载 作者:行者123 更新时间:2023-11-28 22:50:23 27 4
gpt4 key购买 nike

如何在 cython 中检查 python 对象的类型?

我的 Cython 扩展 E 在模块 M 中编译为 E.pyd

我正在尝试检查 Cython 扩展 Eclass A 中的 python 参数类型。

cdef class A:
def foo(self, bar):
if bar is A:
print("ok")
else
print("invalid")

问题是当我去使用 python 的扩展时,

from M import E
a = A()
b = A()
a.foo(b)

当我使用 Python 中的 type(b) 时,bar 不是 A,而是 M.E.A

我在 Cython 中尝试过 if bar is M.E.A: 但编译器提示 undeclared name not builtin: M,因为 Cython 不知道该模块。

最佳答案

在 Cython 和 Python 中 is 是对象标识。它不用于检查类型。

  • 你应该写:

    if isinstance(bar, A):
    ...

    如果你想检查 barA 类型还是它的任何子类型

  • if type(bar) is A:
    ...

    如果你想检查 bar 是否恰好是 A 类型。

或者 Cython 通过以下方式提供类型检查:

def foo(self, A bar):

这也允许用户传递 None 表示没有对象。如果你想排除 None 写:

def foo(self, A bar not None):

参见 Cython docs on extension types

关于python - Cython - 检查对象类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22693375/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com