python-3.x - numba jitclass 中的对象比较

标签 python-3.x jit numba

如何比较两个 numba jitclass 对象以查看它们是否相同?

我有以下代码

from numba import jitclass
import numba

node_type = numba.deferred_type()
DoubleLinkedNode_spec = [
  ('value', numba.optional(numba.typeof(1.0))),
  ('prev', numba.optional(node_type)),
  ('next', numba.optional(node_type))
]

@jitclass(DoubleLinkedNode_spec)
class DoubleLinkedNode(object):
  def __init__(self, value, prev, next):
    self.value = value
    self.prev = prev
    self.next = next

node_type.define(DoubleLinkedNode.class_type.instance_type)

n1 = DoubleLinkedNode(1.0, None, None)
n2 = DoubleLinkedNode(2.0, n1, None)
n1.next = n2
print(f'{n2}\n{n2.prev.next}')
#outputs: 
#  <numba.jitclass.boxing.DoubleLinkedNode object at 0x7fbf26923850>
#  <numba.jitclass.boxing.DoubleLinkedNode object at 0x7fbf256b3cf0>
print(f'Next is None. n1: {n1.next is None}   n2: {n2.next is None}')
#outputs: 
#  Next is None. n1: False   n2: True

这是双链表的标准节点。

is 运算符不起作用,因为它们不在同一内存地址中。

  1. 为什么会发生这种情况?
  2. 那么如何比较两个对象?
  3. is None 似乎有效。但我可以相信它吗?

最佳答案

Dunder 方法无法与 jitclass 一起正常工作,因此我实现了类似于 __eq__ 的内容。

from numba.experimental import jitclass
import numba

node_type = numba.deferred_type()
DoubleLinkedNode_spec = [
    ('value', numba.optional(numba.typeof(1.0))),
    ('prev', numba.optional(node_type)),
    ('next', numba.optional(node_type))
]

@jitclass(DoubleLinkedNode_spec)
class DoubleLinkedNode(object):
    def __init__(self, value, prev, next):
        self.value = value
        self.prev = prev
        self.next = next

    def equal(self, other):
        return self.prevs_eq(other) and self.nexts_eq(other)

    def prevs_eq(self, other):
        while True:
            if self.prev is None:
                return self.value == other.value
            if not self.value == other.value:
                return False

            self = self.prev
            other = other.prev

    def nexts_eq(self, other):
        while True:
            if self.next is None:
                return self.value == other.value
            if not self.value == other.value:
                return False

            self = self.next
            other = other.next

node_type.define(DoubleLinkedNode.class_type.instance_type)

n1 = DoubleLinkedNode(1.0, None, None)
n2 = DoubleLinkedNode(2.0, n1, None)
n1.next = n2

print(f'{n2.equal(n2.prev.next)}')
# True

你必须调用equal方法,这是不优雅的,但如果你将其重命名为__eq__,它根本不起作用。这适用于我迄今为止测试过的内容。

关于python-3.x - numba jitclass 中的对象比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61641797/

相关文章:

python - 为什么这个高阶函数不通过 mypy 中的静态类型检查?

python - 类型错误 : 'float' object cannot be interpreted as an integer ( python 3. 4 版本)

c# - 有没有内存IL重写的例子(Profiler API)?

python - @jit 减速功能

python - Numba 减慢代码?

python - 快速高效的pandas groupby sum操作

python-3.x - 如何告诉 Spacy 不要使用 retokenizer 将任何单词与撇号分开?

perl - 鹦鹉到底是什么?

python - 使用 pandas 将新数据帧索引到新列中