q0987
q0987

Reputation: 35992

How to define the pass-in parameter for the __init__ in Cython

https://media.readthedocs.org/pdf/cython-docs2/stable/cython-docs2.pdf page: 9/47

cimport cqueue

cdef class Queue:
  cdef cqueue.Queue _c_queue

  def __cinit__(self):
    self._c_queue = cqueue.queue_new()
    if self._c_queue is NULL:
      raise MemoryError()

  def __init__(self, name): # I added this section
    self.name = name # Queue' object has no attribute 'name'

After I build the file and use q = Queue('hello'), the compiler always gives me error as

'Queue' object has no attribute 'name'

Upvotes: 0

Views: 215

Answers (1)

DavidW
DavidW

Reputation: 30909

You were missing a bracket on the __init__ line but I don't think that's the real issue ( - now fixed in an edit)

Your problem is that Cython classes don't have a dictionary by default, so you can only add attributes that you have predefined. Therefore you need to tell it that the class has an attribute called name:

cdef class Queue:
  cdef cqueue.Queue _c_queue
  cdef name # not specifying a type makes it a Python object
  # ...

You may want to make name cdef public so it's accessible from Python too.

As an alternative, you can give the class a dictionary, and that should allow arbitrary attributes to be set at the cost of slower access and a larger object:

cdef class Queue
  cdef cqueue.Queue _c_queue
  cdef dict __dict__
  # ...

This seems to require a reasonably recent (last year or so) version of Cython to work.

Upvotes: 1

Related Questions