Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cython use of cinit()

Tags:

cython

I have:

      cdef class BaseClass():
           def __cinit__(self,char* name):
               print "BaseClass __cinit__()"
               #...
           def __dealloc__():
               print "BaseClass __dealloc__()"
               #...
      cdef class DerClass(BaseClass):
           def __cinit__(self,char* name,int n):
               print "DerClass __cinit__()"
               #...
           def __dealloc__():
               print "DerClass __dealloc__()"
               #...

when i call the DerClass in cyhton happen that the construcor of the BaseClass is called automatically,what it has to print is:

       BaseClass __cinit__()
       DerClass __cinit__()
       DerClass __dealloc__()
       BaseClass __dealloc__()

but it does not,it crash ones that i call the DerClass('Ciao'). why does happen so and how can i avoid calling the cinit of BaseClass. Thank you!

like image 411
Alex Vl Avatar asked Oct 06 '11 13:10

Alex Vl


1 Answers

The above answer may not pose quite the best solution. Reading the section "Initialisation methods: __cinit__() and __init__()" of the link above gives this information:

If your extension type has a base type, the __cinit__() method of the base type is automatically called before your __cinit__() method is called; you cannot explicitly call the inherited __cinit__() method.

and

If you anticipate subclassing your extension type in Python, you may find it useful to give the __cinit__() method * and ** arguments so that it can accept and ignore extra arguments.

So my solution would be to just replace the arguments of __cinit()__ in BaseClass so that a variable number of arguments can be passed to any derived class:

cdef class BaseClass:
    def __cinit__(self, *argv): 
        print "BaseClass __cinit__()"
        #...
def __dealloc__(self):
        print "BaseClass __dealloc__()"
        #...

cdef class DerClass(BaseClass):
    def __cinit__(self,char* name, int n):
        print "DerClass __cinit__()"
        #...
    def __dealloc__(self):
        print "DerClass __dealloc__()"
        #...

See here for an explanation of the *args variable in python

like image 112
alexabate Avatar answered Sep 17 '22 15:09

alexabate