在 Python 中:
len(a)
可以替换为a.__len__()
str(a)
或repr(a)
可以替换为a.__str__()
或a.__repr__()
==
是__eq__
,+
是__add__
, 等等
有没有类似的方法来获取id(a)
?如果没有,是否有任何解决方法可以在不使用的情况下获取 python 对象的唯一 ID id()
?
编辑:附加问题:如果不是?有什么理由不定义 a__id__()
吗?
在 Python 中:
len(a)
可以替换为a.__len__()
str(a)
或repr(a)
可以替换为a.__str__()
或a.__repr__()
==
是__eq__
,+
是__add__
, 等等有没有类似的方法来获取id(a)
?如果没有,是否有任何解决方法可以在不使用的情况下获取 python 对象的唯一 ID id()
?
编辑:附加问题:如果不是?有什么理由不定义 a__id__()
吗?
No, this behavior cannot be changed. id()
is used to get "an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime" (source). No other special meaning is given to this integer (in CPython it is the address of the memory location where the object is stored, but this cannot be relied upon in portable Python).
Since there is no special meaning for the return value of id()
, it makes no sense to allow you to return a different value instead.
Further, while you could guarantee that id()
would return unique integers for your own objects, you could not possibly satisfy the global uniqueness constraint, since your object cannot possibly have knowledge of all other living objects. It would be possible (and likely) that one of your special values clashes with the identity of another object alive in the runtime. This would not be an acceptable scenario.
If you need a return value that has some special meaning then you should define a method where appropriate and return a useful value from it.
An object isn't aware of its own name (it can have many), let alone of any unique ID it has associated with it. So - in short - no. The reasons that __len__
and co. work is that they are bound to the object already - an object is not bound to its ID.