python是面向对象的解释性语言,然而python是通过C语言实现的,C语言怎么跟面向对象扯上了关系? C语言可以实现面向对象的性质?
原文链接:http://blog.csdn.net/ordeder/article/details/25296307
#define PyObject_HEAD \
_PyObject_HEAD_EXTRA \
Py_ssize_t ob_refcnt; \
struct _typeobject *ob_type;
以上宏等价于:
Py_ssize_t ob_refcnt;
struct _typeobject *ob_type;
参数: ob_refcnt 作为引用计数(类似智能指针的概念),当引用计数为0的时候对象及被销毁。
参数:_typeobject 即 PyTypeObject实现如下:在python中,一切对对象,包括类型也是一种对象。
typedef struct _typeobject {
PyObject_VAR_HEAD
const char *tp_name; /* For printing, in format "." */
Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */
/* Methods to implement standard operations */
destructor tp_dealloc;
printfunc tp_print;
getattrfunc tp_getattr;
setattrfunc tp_setattr;
cmpfunc tp_compare;
reprfunc tp_repr;
/* Method suites for standard classes */
PyNumberMethods *tp_as_number;
PySequenceMethods *tp_as_sequence;
PyMappingMethods *tp_as_mapping;
...
allocfunc tp_alloc;
newfunc tp_new;
freefunc tp_free; /* Low-level free-memory routine */
inquiry tp_is_gc; /* For PyObject_IS_GC */
PyObject *tp_bases;
PyObject *tp_mro; /* method resolution order */
PyObject *tp_cache;
PyObject *tp_subclasses;
PyObject *tp_weaklist;
destructor tp_del;
...
} PyTypeObject;
typedef struct _object {
PyObject_HEAD
} PyObject;
typedef struct {
PyObject_HEAD
long ob_ival;
} PyIntObject;
typedef struct _dictobject PyDictObject;
struct _dictobject {
PyObject_HEAD
Py_ssize_t ma_fill; /* # Active + # Dummy */
...
PyDictEntry *ma_table;
...
};
通过对比PyIntObject和PyDictObject可得:类PyIntObject和PyDictObject都继承了基类PyObject(PyObject_HEAD)。
PyIntObject和PyDictObject对PyObject_HEAD中的ob_type的赋值是不同的,分别为:
PyTypeObject PyInt_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
"int",
sizeof(PyIntObject),
0,
(destructor)int_dealloc, /* tp_dealloc */
(printfunc)int_print, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
(cmpfunc)int_compare, /* tp_compare */
...
int_new, /* tp_new */
(freefunc)int_free, /* tp_free */
};
PyTypeObject PyDict_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
"dict",
sizeof(PyDictObject),
0,
(destructor)dict_dealloc, /* tp_dealloc */
(printfunc)dict_print, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
(cmpfunc)dict_compare, /* tp_compare */
...
dict_new, /* tp_new */
PyObject_GC_Del, /* tp_free */
};
PyObject *ppy = &pydictobj;
ppy -> ob_type -> tp_print 即为: pyintobj -> ob_type -> dict_print
总结:多态,通过不同类对ob_type进行初始化,为通用函数接口注册相应的回调函数,即可实现了多态;