【问题标题】:compile python class with numba用 numba 编译 python 类
【发布时间】:2022-01-23 23:17:13
【问题描述】:

我正在使用numba.jitclass() 装饰器来编译一个python 类Honda,它将另一个python 类Car 作为输入参数:

class Car(object):
    cc = '10'

class Honda(object):
    def __init__(self):
        self.car = Car()

    def cal(self):
        'Do heavy calculations'

Numba 无法识别 python 对象(类)的类型!

object = Car()
numba.typeof(object)      # Error (not numba type)

试用 _ 1(不工作)

from numba.experimental import jitclass
from numba import types, jit, njit

@jitclass([('car', types.pyobject)])  # I tried to add `nopython=False`, but raise error
class Honda(object):
    def __init__(self):
        self.car = Car()
    
    @jit
    def cal(self):  # TypeError: class members are not yet supported
        'Do heavy calculations'

试用 _ 2(不工作)

@jitclass([('car', types.pyobject)])  # I tried to add `nopython=False`, but raise error
class Honda(object):
    def __init__(self):
        self.car = typed.pyobject(Car())

    @jit
    def cal(self):  # TypeError: class members are not yet supported
        'Do heavy calculations'

试用 _ 3(不工作)

@jitclass() 
class Honda(object, Car):
    def __init__(self):
        pass

    @jit
    def cal(self):  # TypeError: class members are not yet supported
        'Do heavy calculations'

如何在由 numba.jitclass() 编译的类中简单地使用任何 python 对象(任何类类型)?并添加要使用的类成员(@njit 方法)?

有没有比numba.jitclass() 更好的方法来实现这一点?

【问题讨论】:

  • 如何创建一个单独的函数来执行繁重的计算(在类范围之外),然后在实例方法中调用它?
  • 谢谢,是的,我正在尝试使用单独的函数

标签: python numba jit


【解决方案1】:

如果你想在 jitclass 中使用一个类,你也需要把它变成一个 jitclass。

但是:

@nb.experimental.jitclass
class Car0:
    cc = "10"

生产

TypeError: class members are not yet supported: cc

如果您可以使用实例成员而不是类成员,它将编译。例如:

@nb.experimental.jitclass
class Car:
    _cc: str

    def __init__(self, cc: str):
        self._cc = cc

    def cc(self) -> str:
        return self._cc + " cc"

检查:

>>> c = Car("10")
>>> c.cc()
'10 cc'

那你就可以在二等舱使用了。声明它的类型是丑陋的,但它有效:

car_type = nb.typeof(Car("10"))

@nb.experimental.jitclass
class Honda:
    car: car_type

    def __init__(self):
        self.car = Car("20")

    def cal(self) -> str:
        return self.car.cc()

检查:

>>> h = Honda()
>>> h.cal()
'20 cc'

【讨论】:

  • 感谢您的回答。不幸的是,我的设置是使用类
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多