小编mos*_*gui的帖子

将 NumPy 数组作为参数传递给 numba.cfunc

我一直在与一个我无法解决的问题作斗争,因此不太知道如何开始解决它。我在C语言编程方面的经验非常有限,我认为这就是我无法取得进步的原因。

\n\n

我有一些函数使用numpy.interpscipy.integrate.quad来执行一定的积分。自从我使用quad集成,并且根据其文档:

\n\n
\n

要集成的 Python 函数或方法。如果func采用多个参数,则沿第一个参数对应的轴进行积分。

\n\n

如果用户希望提高集成性能,则f可能是\n scipy.LowLevelCallable之一:

\n\n
double func(double x)\ndouble func(double x, void *user_data) \ndouble func(int n, double *xx) \ndouble func(int n, double *xx, void *user_data) \n
Run Code Online (Sandbox Code Playgroud)\n\n

user_data 是包含在scipy.LowLevelCallable. 在 的调用形式中xx,是包含的数组n的长度xxxx[0] == x,其余项是quad 的 args 参数中包含的数字。

\n\n

此外,还支持某些 ctypes 调用签名以实现向后兼容,但这些签名不应在新代码中使用。

\n
\n\n

我需要使用这些scipy.LowLevelCallable对象来加速我的代码,并且我需要将我的函数设计坚持上述签名之一。此外,由于我不想使用 C 库和编译器使整个事情变得复杂,所以我想使用 中提供的工具“即时”解决这个问题numba,特别是numba.cfunc,这允许我绕过 Python C …

c python scipy python-3.x numba

7
推荐指数
1
解决办法
2950
查看次数

类装饰器禁用 __init_subclass__

我四处寻找这个问题的答案,但找不到任何东西。如果之前已经问过这个,我很抱歉。

在我知道的 3-4 种从父类强制执行子类上的给定方法(编辑__new__元类的方法,挂钩到builtins.__build_class__,使用__init_subclass__或使用abc.abstractmethod)中,我通常最终使用__init_subclass__,主要是因为易于使用并且,与 不同@abc.abstractmethod的是,在子类定义而不是类实例化时检查子类上的约束。例子:

class Par():
    def __init_subclass__(self, *args, **kwargs):
        must_have = 'foo'
        if must_have not in list(self.__dict__.keys()):
            raise AttributeError(f"Must have {must_have}")

    def __init__(self):
        pass

class Chi(Par):
    def __init__(self):
        super().__init__()
Run Code Online (Sandbox Code Playgroud)

这个示例代码显然会抛出一个错误,因为Chi没有foo方法。尽管如此,我还是偶然发现了一个事实,即可以通过使用一个简单的类装饰器来绕过来自上游类的这个约束:

def add_hello_world(Cls):
    class NewCls(object):
        def __init__(self, *args, **kwargs):
            self.instance = Cls(*args, **kwargs)

        def hello_world(self):
            print("hello world")

    return NewCls


@add_hello_world
class Par:
    def __init_subclass__(self, *args, **kwargs):
        must_have = "foo"
        if must_have not in …
Run Code Online (Sandbox Code Playgroud)

python inheritance subclass decorator python-3.x

2
推荐指数
1
解决办法
245
查看次数

标签 统计

python ×2

python-3.x ×2

c ×1

decorator ×1

inheritance ×1

numba ×1

scipy ×1

subclass ×1