0

I create a simple class in python and check whether it has a certain attribute. After hasattr() Return True I try to rewrite it in Cython and but then hasattr() returns False.

Look at this example in python:

class Foo_p:
    def __init__(self, val):
        self.val = val
    def printVal(self):
        print(self.val)

a=Foo_p(5)
print(hasattr(a,"val"))

this example prints "True".

Now I try to rewrite it in Cython:

%load_ext Cython
%%cython
cdef class Foo_c:
    cdef int val

    def __init__(self, int val):
        self.val = val
    def printVal(self):
        print(self.val)

b=Foo_c(5)
print(hasattr(b,"val"))

and now it prints "False"

Does anyone has an idea of what has happend?

  • 2
    I'm not convinced that this is _quite_ a duplicate of https://stackoverflow.com/questions/55230665/cython-class-attributeerror but it's pretty close. – DavidW Aug 04 '19 at 17:29
  • I think the code in the Cython version is changing the _class_ attribute named `val`, not creating an _instance_ attribute with that name which is what the Python version does. – martineau Aug 04 '19 at 17:32
  • @martineau but `hasattr` should return `True` for class attributes too – DeepSpace Aug 04 '19 at 17:33
  • @DeepSpace: It does for Python code, not sure about Cython though... Regardless, this isn't an apples-to-apples comparison. – martineau Aug 04 '19 at 17:35
  • @DavidW Thank you, the problem was solved by writing cdef public class Foo_c: instead of cdef class Foo_c: – Oran Szachter Aug 04 '19 at 17:36

0 Answers0