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

Asked

Viewed 812 times

3

Researching, I noticed that the function id() returns an integer and that guarantees to be unique and constant to the object.

When comparing two objects I got different results, which may have enabled these different results??

I observed in a booklet that the comparison id(Carro()) == id(Carro()) returns False but when executing the code the same returned True

Car Class.py

class Carro:
    pass

Code in the Idle

>>> from Carro import Carro
>>> fusca = Carro()
>>> opala = Carro()
>>> id(opala) == id(fusca)
False
>>> id(Carro()) == id(Carro())
True
  • Good question, it was to give False, since two distinct objects of the type are being created Carro

  • Exactly @Haroldo_ok , wait for someone to describe what may have occurred.

1 answer

1

In reality you did not create two instances in:

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

that’s why True:

See the code below, it works on 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.