0

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?

8
  • 1
    Not sure about CYthon, but this you would expect in plain python. Why are you using property? Commented Mar 18, 2020 at 19:19
  • @juanpa.arrivillaga Because I want access to this attribute later on python workspace Commented Mar 18, 2020 at 19:21
  • So? You don't need property for 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 the property altogether. Commented Mar 18, 2020 at 19:41
  • 1
    This will be a duplicate of either stackoverflow.com/questions/42632297/… or stackoverflow.com/questions/55230665/…. For a cdef class you must declare the attributes and to access them from Python you must make them public. And if you want to use property make sure you understand what it does in Python Commented Mar 18, 2020 at 20:14
  • 1
    The declaration needs to be outside __init__ at the class level. However it cannot be for type np.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. Commented Mar 19, 2020 at 6:02

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.