您缺少图片的关键部分:实际的日期时间结构定义,位于Include/datetime.h。里面也有重要的评论。以下是一些关键摘录:
/* Fields are packed into successive bytes, each viewed as unsigned and
* big-endian, unless otherwise noted:
*
* byte offset
* 0 year 2 bytes, 1-9999
* 2 month 1 byte, 1-12
* 3 day 1 byte, 1-31
* 4 hour 1 byte, 0-23
* 5 minute 1 byte, 0-59
* 6 second 1 byte, 0-59
* 7 usecond 3 bytes, 0-999999
* 10
*/
...
/* # of bytes for year, month, day, hour, minute, second, and usecond. */
#define _PyDateTime_DATETIME_DATASIZE 10
...
/* The datetime and time types have hashcodes, and an optional tzinfo member,
* present if and only if hastzinfo is true.
*/
#define _PyTZINFO_HEAD \
PyObject_HEAD \
Py_hash_t hashcode; \
char hastzinfo; /* boolean flag */
...
/* All datetime objects are of PyDateTime_DateTimeType, but that can be
* allocated in two ways too, just like for time objects above. In addition,
* the plain date type is a base class for datetime, so it must also have
* a hastzinfo member (although it's unused there).
*/
...
#define _PyDateTime_DATETIMEHEAD \
_PyTZINFO_HEAD \
unsigned char data[_PyDateTime_DATETIME_DATASIZE];
typedef struct
{
_PyDateTime_DATETIMEHEAD
} _PyDateTime_BaseDateTime; /* hastzinfo false */
typedef struct
{
_PyDateTime_DATETIMEHEAD
unsigned char fold;
PyObject *tzinfo;
} PyDateTime_DateTime; /* hastzinfo true */
另外,请注意以下事项lines in Modules/_datetimemodule.c
:
static PyTypeObject PyDateTime_DateTimeType = {
PyVarObject_HEAD_INIT(NULL, 0)
"datetime.datetime", /* tp_name */
sizeof(PyDateTime_DateTime), /* tp_basicsize */
That tp_basicsize
线说sizeof(PyDateTime_DateTime)
, not sizeof(_PyDateTime_BaseDateTime)
,并且该类型没有实现任何特殊的__sizeof__
处理。这意味着datetime.datetime
type 将其实例大小报告为时区感知日期时间的大小,即使对于不感知的实例也是如此。
您看到的 48 字节计数细分如下:
- 8 字节引用计数
- 8字节类型指针
- 8 字节缓存哈希
- 1 字节“hastzinfo”标志
- 10字节手动打包
unsigned char[10]
包含日期时间数据
- 1 字节“折叠”标志(夏令时相关)
- 4 字节填充,用于对齐 tzinfo 指针
- 8字节tzinfo指针
即使您的不知情实例的实际内存布局没有折叠标志或 tzinfo 指针,情况也是如此。
当然,这就是所有实现细节。在不同的 Python 实现、不同的 CPython 版本、32 位 CPython 构建或 CPython 调试构建上,它可能会有所不同(当使用定义的 Py_TRACE_REFS 编译 CPython 时,PyObject_HEAD 中会有额外的内容)。