Re: extension type attributes
Mark Ellis <[email protected]> Sun, 31 May 2009 17:19:18 +0100
| Newsgroups | gmane.comp.python.pyrex |
|---|---|
| Message-ID | <1243786758.4897.2.camel@mark01> |
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 _______________________________________________ Pyrex mailing list [email protected] http://lists.copyleft.no/mailman/listinfo/pyrex
signature.asc
(application/pgp-signature, 197 B)
-----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (GNU/Linux) iEYEABECAAYFAkoirgYACgkQkQq5eu6iQvDNkgCfd7jgKAM5c+183FUl9Op0o1dg og4AnArRkKtq2cWsiQHwkbfyoJ6pPYMf =M8sn -----END PGP SIGNATURE-----