Comparison between two objects in Python using the id () function with different result

1

Searching, I noticed that the id() function returns an integer and ensures that it is unique and constant for the object.

When comparing two objects I get different results, what may have made these different results possible?

I noticed in a book that the comparison id(Carro()) == id(Carro()) returns False but when executing the code it returned True

Car.py class

class Carro:
    pass

Idle code

>>> from Carro import Carro
>>> fusca = Carro()
>>> opala = Carro()
>>> id(opala) == id(fusca)
False
>>> id(Carro()) == id(Carro())
True
    
asked by anonymous 20.10.2016 / 19:03

1 answer

1

In fact you did not create two instances in:

>>> id(Carro()) == id(Carro())  # True

So it's True:

See the code below, it works in python2 or python3

>>> from carro import Carro
>>> fusca = Carro()
>>> opala = Carro()
>>> id(opala) == id(fusca)
False
>>> id(Carro()) == id(Carro())
True
>>> a = id(Carro()) 
>>> b = id(Carro())
>>> a
140356195163608
>>> b
140356195163720
>>> id(Carro())
140356195163608
    
31.10.2016 / 20:15