为什么njit函数在类内部不起作用,但在类外部起作用?

2024-04-26 05:19:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我不明白为什么函数compute在类myclass之外时工作,但在类内时不工作

import numpy as np
from numba import njit

@njit
def compute(length):
    x=np.zeros(length)
    for i in range(length):
        x[i] = i
    return x

class myclass():
    def __init__(self):
        self.length = 100

    def Simule(self):
        res = compute(self.length)
        print(res)

    def Simule2(self):
        res = self.compute(self.length)
        print(res)

    @njit
    def compute(self, length):
        x = np.zeros(length)
        for i in range(length):
            x[i] = i
        return x


if __name__ == "__main__":
    instance = myclass()
    instance.Simule()
    instance.Simule2()

Tags: instanceinimportselfforreturndefnp
1条回答
网友
1楼 · 发布于 2024-04-26 05:19:06

似乎此装饰程序无法识别装饰的callabe是函数还是方法,您可以将其更改为staticmethod:

import numpy as np
from numba import njit

@njit
def compute(length):
    x=np.zeros(length)
    for i in range(length):
        x[i] = i
    return x

class myclass():
    def __init__(self):
        self.length = 100

    def Simule(self):
        res = compute(self.length)
        print(res)

    def Simule2(self):
        res = self.compute(self.length)
        print(res)

    @staticmethod
    @njit
    def compute(length):
        x = np.zeros(length)
        for i in range(length):
            x[i] = i
        return x


if __name__ == "__main__":
    instance = myclass()
    instance.Simule()
    instance.Simule2()

相关问题 更多 >