gpt4 book ai didi

python - 在 Cython 类中,使用 __init__ 和 __cinit__ 有什么区别?

转载 作者:行者123 更新时间:2023-12-03 21:12:31 24 4
gpt4 key购买 nike

代码块 1 使用 __init__

%%cython -3
cdef class c:
cdef:
int a
str s
def __init__(self):
self.a=1
self.s="abc"
def get_vals(self):
return self.a,self.s
m=c()
print(m.get_vals())
代码块 2 使用 __cinit__
%%cython -3
cdef class c:
cdef:
int a
str s
def __cinit__(self): # cinit here
self.a=1
self.s="abc"
def get_vals(self):
return self.a,self.s
m=c()
print(m.get_vals())
  • 我测试了这两个代码,并且都运行没有错误。
    在这种情况下,使用 __cinit__ 有什么意义?而不是 __init__ ?
  • 看了官方的文章,被一句话搞糊涂了:

    If you need to pass a modified argument list to the base type, you will have to do the relevant part of the initialization in the __init__() method instead, where the normal rules for calling inherited methods apply.



  • “修改后的论点”是什么意思?在这里,我为什么要使用 init 而不是 cinit?

    最佳答案

    主要是关于继承。假设我从你的类(class)继承 C :

    class D(C):
    def __init__(self):
    pass # oops forgot to call C.__init__

    class E(C):
    def __init__(self):
    super().__init__(self)
    super().__init__(self) # called it twice
    如何 __init__最终被调用完全取决于从它继承的类。请记住,可能存在多层继承。
    此外, a fairly common pattern for creating classes that wrap C/C++ objects is to create a staticmethod cdef function as an alternative constructor :
    cdef class C:
    def __cinit__(self):
    print("In __cinit__")

    @staticmethod
    cdef make_from_ptr(void* x):
    val = C.__new__(C)
    # do something with pointer
    return val
    在这种情况下, __init__通常不调用。
    相比之下 __cinit__保证只被调用一次,这在流程的早期阶段由 Cython 自动发生。当您拥有 cdef 时,这是最重要的。您的类在初始化时所依赖的属性(例如 C 指针)。 Python 派生类甚至无法设置这些,但是 __cinit__可以确保他们是。
    在您的情况下,这可能无关紧要 - 使用您满意的任何一个。

    就“修改参数”而言,它是说你不能用 __cinit__ 复制它。 :
    class NameValue:
    def __init__(self, name, value):
    self.name = name
    self.value = value

    class NamedHelloPlus1(NamedValue):
    def __init__(self, value):
    super().__init__("Hello", value+1)
    NamedHelloPlus1控制什么参数 NamedValue得到。与 __cinit__ Cython 所有对 __cinit__ 的调用接收完全相同的参数(因为 Cython 安排了调用 - 您不能手动调用它)。

    关于python - 在 Cython 类中,使用 __init__ 和 __cinit__ 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62827538/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com