c
#include <Python.h>
typedef struct {
PyObject_HEAD
double x;
double y;
} Point;
static PyObject* Point_new(PyTypeObject *type, PyObject *args, PyObject *kwds) {
Point *self;
self = (Point *)type->tp_alloc(type, 0);
if (self != NULL) {
self->x = 0.0;
self->y = 0.0;
}
return (PyObject *)self;
}
static void Point_dealloc(Point *self) {
self->ob_type->tp_free((PyObject *)self);
}
static int Point_init(Point *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_get_x(Point *self, void *closure) {
return PyFloat_FromDouble(self->x);
}
static int Point_set_x(Point *self, PyObject *value, void *closure) {
if (value == NULL) {
PyErr_SetString(PyExc_TypeError, "Cannot delete the x attribute");
return -1;
}
if (!PyFloat_Check(value)) {
PyErr_SetString(PyExc_TypeError, "The x attribute value must be a float");
return -1;
}
self->x = PyFloat_AsDouble(value);
return 0;
}
static PyObject* Point_get_y(Point *self, void *closure) {
return PyFloat_FromDouble(self->y);
}
static int Point_set_y(Point *self, PyObject *value, void *closure) {
if (value == NULL) {
PyErr_SetString(PyExc_TypeError, "Cannot delete the y attribute");
return -1;
}
if (!PyFloat_Check(value)) {
PyErr_SetString(PyExc_TypeError, "The y attribute value must be a float");
return -1;
}
self->y = PyFloat_AsDouble(value);
return 0;
}
static PyGetSetDef Point_getsetters[] = {
{"x", (getter)Point_get_x, (setter)Point_set_x, "x coordinate", NULL},
{"y", (getter)Point_get_y, (setter)Point_set_y, "y coordinate", NULL},
{NULL} /* Sentinel */
};
static PyTypeObject PointType = {
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
"point.Point", /*tp_name*/
sizeof(Point), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor)Point_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT, /*tp_flags*/
"Point object", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
0, /* tp_members */
Point_getsetters, /* 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;
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);
}