I want to change an attribute from a class within Cython, and I don't really understand why the following code gives rise to an error:
%%cython -a
import numpy as np
cimport numpy as np
cdef class Prueba:
def __init__(self, np.ndarray[np.float64_t] x, np.ndarray[np.float64_t] y):
self.x = x
self.y = y
@property
def x(self):
return self.x
@property
def y(self):
return self.y
cpdef np.ndarray[np.float64_t] change_x(self, np.ndarray[np.float64_t] new):
self.x = new
return self.x
>
A = Prueba(np.random.uniform(size=5),np.random.uniform(size=5))
>
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-25-2129c60d0253> in <module>
----> 1 A = Prueba(np.random.uniform(size=5),np.random.uniform(size=5))
2 A
_cython_magic_2cd24205d75c05a3b692d063afd9549d.pyx in
_cython_magic_2cd24205d75c05a3b692d063afd9549d.Prueba.__init__()
AttributeError: attribute 'x' of '_cython_magic_2cd24205d75c05a3b692d063afd9549d.Prueba'
objects is not writable
What is the problem here?
property?propertyfor that. In any case, the problem is you haven't defined a setter, but if all that is going to do is set the attribute, just remove thepropertyaltogether.cdef classyou must declare the attributes and to access them from Python you must make them public. And if you want to usepropertymake sure you understand what it does in Python__init__at the class level. However it cannot be for typenp.ndarray[np.float64_t](a buffer type). jttps://stackoverflow.com/questions/8808216/cython-buffer-declarations-for-object-members. Instead either don't type it (cdef public x,y) or use the newer memoryview types.