Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #18985

Re: defining class and subclass in C

From Daniel Franke <franke.daniel@gmail.com>
Subject Re: defining class and subclass in C
Date 2012-01-15 00:29 +0100
References <2921241.kWnIB6QQbB@silence>
Newsgroups comp.lang.python
Message-ID <mailman.4755.1326583786.27778.python-list@python.org> (permalink)

Show all headers | View raw


On Saturday 14 January 2012 22:15:36 Daniel Franke wrote:
> Here I'd expect "<class 'ca.ca'>" instead?! And I never managed a proper
> subclass :|

Found an explanation on type/class at [1]: "he difference between the two is 
whether the C-level type instance structure is flagged as having been 
allocated on the heap or not" - hu?

With this info, I went ahead and tried the code quoted below. Now I get:

>>> import cmod
>>> cmod.ca
<type 'cmod.ca'>
>>> cmod.cb
<type 'cmod.cb'>
>>> cmod.ca.__bases__
(<type 'object'>,)
>>> cmod.cb.__bases__
(<type 'cmod.ca'>,)

which seems to make sense besides the "type" instead of "class"?!

What threw me is that I expected that I'd need to explicitly subclass the 
"object" type, from which I assumed for some reason I'd also inherit the 
.tp_new member. This is obviously not the case.

Now the last question is, how do I get the a_type of Python class to use it as 
base for "cb"?

On lives and learns.

	Daniel


[1] http://utcc.utoronto.ca/~cks/space/blog/python/ClassesAndTypes

--
#include <Python.h>

typedef struct {
  PyObject_HEAD
} ca;

static PyTypeObject ca_Type = {
  PyObject_HEAD_INIT(NULL)
};


typedef struct {
  PyObject_HEAD
} cb;

static PyTypeObject cb_Type = {
  PyObject_HEAD_INIT(NULL)
};


PyMODINIT_FUNC initcmod(void) {
  PyObject *cmod;

  ca_Type.tp_name      = "cmod.ca";
  ca_Type.tp_basicsize = sizeof(ca);
  ca_Type.tp_flags     = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE;
  ca_Type.tp_new       = PyType_GenericNew;
  ca_Type.tp_base      = &PyBaseObject_Type;

  if (PyType_Ready(&ca_Type) < 0)
    return;

  cb_Type.tp_name      = "cmod.cb";
  cb_Type.tp_basicsize = sizeof(cb);
  cb_Type.tp_flags     = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE;
  cb_Type.tp_base      = &ca_Type;

  if (PyType_Ready(&cb_Type) < 0)
    return;

  cmod = Py_InitModule3("cmod", NULL, "c module");
  if (cmod == NULL)
    return;

  Py_INCREF(&ca_Type);
  PyModule_AddObject(cmod, "ca", (PyObject*)&ca_Type);

  Py_INCREF(&cb_Type);
  PyModule_AddObject(cmod, "cb", (PyObject*)&cb_Type);
}

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: defining class and subclass in C Daniel Franke <franke.daniel@gmail.com> - 2012-01-15 00:29 +0100

csiph-web