Reputation: 331
Let's have an example.
cdef class Example:
attr2 = None
cdef attr3
cdef object attr4
def __init__(self):
self.attr1 = Obj()
self.attr2 = Obj()
self.attr3 = Obj()
self.attr4 = Obj()
The line with the assignment to self.attr1 will raise an AttributeError saying: "object has no attribute 'attr1'.
If try with the self.attr2 it raises also the exception but with the message: "object attribute 'attr2' is read-only".
And if uses the keyword cdef, an it doesn't have an explicit type, the compilation process will fail.
If this attribute is defined with the type object, it looks nice. But different instances of the Example class will have this attr4 like a singleton and any interaction with one of them will be visible for the other instances and, in this case, I want to have an Obj() instance unique for each of them.
Upvotes: 0
Views: 1946
Reputation: 5443
You can try something like this :
class Obj(object):
# At first I define a class Obj() to match your example
def __init__(self):
self.abc = 32
self.xyz = "xyzxyz"
# Then I can define the Example class
cdef class Example:
cdef public:
object attr1, attr2, attr3, attr4
def __init__(self):
self.attr1 = Obj()
self.attr2 = Obj()
self.attr3 = Obj()
self.attr4 = Obj()
It seems to be cythonized/compiled without error and you have access to the attributes related to the Obj
object :
In [11]:
a = Example()
a.attr1.abc
Out[11]:
32
Upvotes: 1