Python类中私有的太极func无法被太极kernel调用

在一个@ti.data_oriented的python类中,无法通过该类中的ti.kernel调用私有ti.func。

以下代码可以复现:

import taichi as ti

ti.init(arch=ti.cpu)

@ti.data_oriented
class sample_class():
    def __init__(self, patch_size: int):
        self.patch = ti.Vector([i for i in range(patch_size)],dt = ti.f32)

    @ti.kernel
    def run_func(self):
        self.__func()

    @ti.func
    def __func(self):
        print("a patch", self.patch)

obj = sample_class(5)
obj.run_func()
  • 直接运行会报: ‘sample_class’ object has no attribute ‘__func’
  • 移除 run_func()的太极修饰符,并将 __func()的修饰符改为ti.kernel,可以顺利运行
  • 移除 run_func()和__func()的太极修饰符,也可以正常运行。

我猜想这可能和私有成员被命名为 _classname__name 有关。可是不明白为什么python scope 直接调用私有的ti.kernel没有问题,但kernel调用私有的ti.func会报错呢?

感谢解答!

确实和私有成员被命名为 _classname__name有关。python语法在类的成员函数里是可以直接调用__func的,但是在类外面就只能调用obj._sample_class__func。然而太极在生成kernel的时候会读取kernel的AST,在这个读取过程中taichi找不到obj.__func,如果改成self._sample_class__func是可以运行的。我看看可不可以处理的时候自动加上_sample_class的前缀。

感谢解答,明白了。