Pergunta

In Python:

  • len(a) can be replaced by a.__len__()
  • str(a) or repr(a) can be replaced by a.__str__() or a.__repr__()
  • == is __eq__, + is __add__, etc.

Is there similar method to get the id(a) ? If not, is there any workaround to get an unique id of a python object without using id() ?


edit: additional question: if not ? is there any reason not to define a __id__() ?

Foi útil?

Solução

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.

Outras dicas

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top