Embeding Py: failed to instantiate a class
Brano Zarnovican
zarnovican at pobox.sk
Tue Mar 22 02:39:07 EST 2005
Hi !
I need to import a module and create an instance
of a class from that module (in C).
import mod
o = mod.klass()
(mod.klass is a subclass of tuple)
When I receive a class object from the module..
module = PyImport_ImportModule("mod")
cls = PyObject_GetAttrString(module, "klass")
..it fails the PyClass_Check(cls) check.
Some classes pass the check, like:
class test1:
pass
class test3(test1):
pass
but most don't. It is enough to subclass
a buildin type. E.g. this class fails the check:
class test2(object):
pass
Q: Do I need to initialize the class object before
using ? How ?
I have found similar questions in this group, but
no "do-it-this-way" answer. It looks that new-style
classes have a different C API semantic than old ones.
To rephrase my question:
Q: Can you give an example code of creating an instance
of new-style class ?
Thanks,
BranoZ
PS: Below are some example code used to test it.
--- mod.py ---
class test1:
pass
class test2(object):
pass
class test3(test1):
pass
--- main.c ---
#include <Python.h>
static PyObject *module = NULL;
void check(char *name) {
PyObject *cls = NULL;
printf("%s - ", name);
if ((cls=PyObject_GetAttrString(module, name)) == NULL) {
PyErr_Print();
return;
}
PyObject_Print(cls, stdout, 0);
if (!PyClass_Check(cls))
printf(" - not a class!!\n");
else
printf(" - is a class.\n");
}
int main(int argc, char *argv[]) {
Py_Initialize();
if ((module=PyImport_ImportModule("mod")) == NULL) {
PyErr_Print();
return -1;
}
check("test1");
check("test2");
check("test3");
Py_Main(argc, argv);
Py_Finalize();
}
--- output ---
$ ./main
test1 - <class mod.test1 at 0x4032da7c> - is a class.
test2 - <class 'mod.test2'> - not a class!!
test3 - <class mod.test3 at 0x4032db3c> - is a class.
Python 2.3 (#2, Feb 9 2005, 13:41:20)
[GCC 3.3.1 (Mandrake Linux 9.2 3.3.1-2mdk)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import mod
>>> mod.test1
<class mod.test1 at 0x4032da7c>
>>> mod.test2
<class 'mod.test2'>
>>> mod.test1()
<mod.test1 instance at 0x40337cac>
>>> mod.test2()
<mod.test2 object at 0x40337cec>
>>>
More information about the Python-list
mailing list