c
#include <Python.h>
typedef struct {
PyObject_HEAD
double x, y;
} PointObject;
static PyObject *Point_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
PointObject *self;
self = (PointObject *)type->tp_alloc(type, 0);
if (self != NULL) {
self->x = 0.0;
self->y = 0.0;
}
return (PyObject *)self;
}
static void Point_dealloc(PointObject *self)
{
self->ob_type->tp_free((PyObject *)self);
}
static int Point_init(PointObject *self, PyObject *args, PyObject *kwds)
{
static char *kwlist[] = {"x", "y", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|dd", kwlist, &self->x, &self->y))
return -1;
return 0;
}
static PyObject *Point_str(PointObject *self)
{
char str[50];
sprintf(str, "(%.2f, %.2f)", self->x, self->y);
return Py_BuildValue("s", str);
}
static PyMethodDef Point_methods[] = {
{NULL} /* sentinel */
};
static PyTypeObject PointType = {
PyObject_HEAD_INIT(NULL)
0, /* ob_size */
"point.Point", /* tp_name */
sizeof(PointObject), /* tp_basicsize */
0, /* tp_itemsize */
(destructor)Point_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
(reprfunc)Point_str, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
(reprfunc)Point_str, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
"Point objects", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
Point_methods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)Point_init, /* tp_init */
0, /* tp_alloc */
Point_new, /* tp_new */
};
static PyMethodDef module_methods[] = {
{NULL} /* sentinel */
};
PyMODINIT_FUNC initpoint(void)
{
PyObject *m;
PointType.tp_new = PyType_GenericNew;
if (PyType_Ready(&PointType) < 0)
return;
m = Py_InitModule3("point", module_methods, "Point module");
if (m == NULL)
return;
Py_INCREF(&PointType);
PyModule_AddObject(m, "Point", (PyObject *)&PointType);
}