[Pyrex] extension type attributes
Mark Ellis
mark at mpellis.org.uk
Sun May 31 18:19:18 CEST 2009
On Fri, 2009-05-29 at 19:29 +0200, Lenard Lindstrom wrote:
> horace wrote:
> > hi,
> >
> > i have a question about extension type attributes.
> >
> > cdef class MyComplex:
> > """A mutable complex number type (incomplete)"""
> > cdef complex *c
> >
> > do all attributes have to be cdef? if i want to have a python object
> > as an attribute i have to use
> >
> > cdef object mypythonobject
> >
> > and then initialize it in __init__()? or did i misunderstand
> > something? i didn't find the manual very clear about this.
> >
> > (i use cython in case this makes any difference.)
> >
> Hi,
>
> The familiar object attributes of Python class instances - class
> Something - are stored in a per object dictionary keyed by attribute
> name. To see this dictionary just do obj.__dict__ for some object
> created from a Python class. Extension types, at least Pyrex/Cython
> extension types, don't have that dictionary. And I don't see any way
> directly enable it. Extension type "attributes" are really just C
> structure fields, so not directly accessible from Python. There are the
> public and readonly qualifiers that automatically create properties for
> a cdef attribute though. So is you what an object attribute accessible
> form Python do something like this:
>
> cdef class MyClass:
> cdef public object x
>
> Attribute x can now be read and altered from Python. Initialize it
> either from __cinit__ or __init__. It will default to None.
>
> If you don't know what the valid attributes will be before hand, then
> the easiest way to add object attributes is to subclass the extension
> type with a normal class:
>
> cdef class _MyClass:
> .....
>
> class MyClass(_MyClass):
> ....
>
> Now the MyClass class has a per object dictionary. Use __init__ to set
> initial values. Make sure the class __init__ function and extension type
> __cinit__ have compatible arguments or one of them will complain.
>
>
Or you could implement __setattr__ and __getattr__ methods for your
class, in which case attributes can be whatever you want. These methods
could then default to accessing a dict object stored as part of the C
class struct, to act as 'normal' python object attributes.
Mark
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 197 bytes
Desc: This is a digitally signed message part
Url : http://lists.copyleft.no/pipermail/pyrex/attachments/20090531/cb1d407c/attachment.bin
More information about the Pyrex
mailing list