need something like __init__ in classes __classinit__

Jens Gelhaar cuiod-tec at web.de
Fri Mar 8 02:31:22 EST 2002


Hi,

I tried it very hard, but no success. What I trying to do is

class test:
   def __classinit__(cls):
      << do something with the new class >>

class testsub(test):
   pass

Every time, when I inherit from class test, the function __classinit__
should be called.
Several month ego, some one gave my the hint to deal with the new type
(metaclass) concept from python 2.2. That was ok and helps me further.
But now I get stucked again. I have to inherit from Persistent (ZODB).
And this class does not work together with metaclass concept of python
2.2.

class metaclass(type):
   def __new__(cls):
       cls.__classinit__(...)

class primary(Persistent):
   __metaclass__=metaclass
   def __classinit__(cls):
     << do something ...>

I get a error message, that I can not inherit from to different
metaclasses.

Now, I had the idea to do it in a complete different way. Lets changed
it in the source and call each function "__classinit__" when a new
class is created. But it worked for "classic" classes, not for
inherited ones from "object" or "Persistent" of ZODB.

Now my question? Where to implement such a call. I did it in
"classobject.c" file, but without success. Beside, I would find it
very useful as a general behaviour. There is "__init__" for a new
instance, why not a "__classinit__" for a new class.

Here what i tried:


static PyObject *
class_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
  PyObject *name, *bases, *dict;
  PyClassObject *op;
  PyClassObject *dummy;
  PyObject *classinit, *res;
  static char *kwlist[] = {"name", "bases", "dict", 0};

  if (!PyArg_ParseTupleAndKeywords(args, kwds, "SOO", kwlist,
       &name, &bases, &dict))
       return NULL;
  op = (PyClassObject *)PyClass_New(bases, dict, name);
  !!!!!!!!!!!!!!! NEW !!!!!!!!!!!!!!!!!!!
  if (classinitstr == NULL)
      classinitstr=PyString_InternFromString("__classinit__");
  if (op != NULL && PyClass_Check(op)) {
     classinit = class_lookup(op, classinitstr, &dummy);
     if ((classinit != NULL)) { // && PyMethod_Check(classinit)) {
         res=PyEval_CallMethod((PyObject *)op, "__classinit__", "(O)",
op);
     }
  }
  !!!!!!!!!!!!!!! END NEW !!!!!!!!!!!!!!!!!!!!!!!!1111
  return (PyObject *)op;
}



More information about the Python-list mailing list