12.4 类型类
>>> t = type("hello")
>>> t
<class 'str'>>>> type(t)
<class 'type'>>>> class example:
... x = 1
>>> i = example()
>>> repr(i)
'<__main__.example object at 0x10b418100>'类型槽
类型槽
前缀
在 C 语言中使用类型
类型属性字典
Last updated
>>> t = type("hello")
>>> t
<class 'str'>>>> type(t)
<class 'type'>>>> class example:
... x = 1
>>> i = example()
>>> repr(i)
'<__main__.example object at 0x10b418100>'Last updated
struct PyTypeObject
---
typedef struct _typeobject {
...
reprfunc tp_repr;
...
} PyTypeObject;typedef PyObject *(*reprfunc)(PyObject *);PyTypeObject PyCell_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
"cell",
sizeof(PyCellObject),
0,
(destructor)cell_dealloc, /* tp_dealloc */
0, /* tp_vectorcall_offset */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_as_async */
(reprfunc)cell_repr, /* tp_repr */
...
};PyObject *
PyObject_GetItem(PyObject *o, PyObject *key)
{
PyMappingMethods *m;
PySequenceMethods *ms;
...ms = o->ob_type->tp_as_sequence;
if (ms && ms->sq_item) {
if (PyIndex_Check(key)) {
Py_ssize_t key_value;
key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
if (key_value == -1 && PyErr_Occurred())
return NULL;
return PySequence_GetItem(o, key_value);
}
else {
return type_error("sequence index must "
"be integer, not '%.200s'", key);
}
}