我的印象是 python 內置函式是物件方法的包裝器。
關于 id()檔案說:
對于 CPython,id(x) 是存盤 x 的記憶體地址。
說到id(),檔案其他地方就不多說了!
我希望 id() 應該使用在后臺傳遞給它的變數 x 的 dunder 方法或屬性之一!它必須是你做的時候可以看到的
目錄(x)
哪一個?例如:
foo = [1,2,3]
dir(foo)
>> ['__add__',
'__class__',
'__contains__',
'__delattr__',
'__delitem__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getitem__',
'__gt__',
'__hash__',
'__iadd__',
'__imul__',
'__init__',
'__init_subclass__',
'__iter__',
'__le__',
'__len__',
'__lt__',
'__mul__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__reversed__',
'__rmul__',
'__setattr__',
'__setitem__',
'__sizeof__',
'__str__',
'__subclasshook__']
uj5u.com熱心網友回復:
python有多種實作。在 cpython 中,所有物件都有一個標準頭,id 是該頭的記憶體地址。對物件的參考是指向其物件頭(即 id 的相同記憶體地址)的 C 指標。您不能使用 dunder 方法來查找物件,因為您需要物件指標來查找 dunder 方法。
Python 被編譯成位元組碼,而該位元組碼由 C 執行。當你呼叫一個函式時id,該函式可以是更多的位元組碼,但它也可以是一個 C 函式。在中搜索“builtin_id” bltinmodule.c,您將看到id(some_object).
static PyObject *
builtin_id(PyModuleDef *self, PyObject *v)
/*[clinic end generated code: output=0aa640785f697f65 input=5a534136419631f4]*/
{
PyObject *id = PyLong_FromVoidPtr(v);
if (id && PySys_Audit("builtins.id", "O", id) < 0) {
Py_DECREF(id);
return NULL;
}
return id;
}
該id函式被呼叫PyObject *v,一個指向應采用其 id 的物件的指標。PyObject是所有 python 物件使用的標準物件頭。它包括確定物件真正是什么型別所需的資訊。該id函式將物件指標轉換為 python 整數PyLong_FromVoidPtr(python int 的名稱“long”有點歷史性)。這就是你在 python 級別看到的 id。
您可以在 github 上獲取cpython 源代碼,并且可以在Extending and Embedding the Python Interpreter and Python/C API Reference Manual的 python 檔案中閱讀 C
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/341433.html
上一篇:僅當PythonPandas中沒有任何值丟失時,如何計算多列的平均值?
下一篇:在檔案中搜索特定資訊
