Ran into the following:
>>> class A:
... def __str__(self):
... return "some A()"
...
>>> class B(A):
... def __str__(self):
... return "some B()"
...
>>> print A()
some A()
>>> print B()
some B()
>>> A.__str__ == B.__str__
False # seems reasonable, since each method is an object
>>> id(A.__str__)==id(B.__str__)
True # what?!
What's going on here?
Definition and Usage. The id() function returns a unique id for the specified object. All objects in Python has its own unique id. The id is assigned to the object when it is created. The id is the object's memory address, and will be different for each time you run the program. (
The == operator compares the value or equality of two objects, whereas the Python is operator checks whether two variables point to the same object in memory. In the vast majority of cases, this means you should use the equality operators == and !=
Python - cmp() function cmp() is an in-built function in Python, it is used to compare two objects and returns value according to the given values. It does not return 'true' or 'false' instead of 'true' / 'false', it returns negative, zero or positive value based on the given input.
The is keyword is used to test if two variables refer to the same object. The test returns True if the two objects are the same object. The test returns False if they are not the same object, even if the two objects are 100% equal. Use the == operator to test if two variables are equal.
As the string id(A.__str__) == id(B.__str__)
is evaluated, A.__str__
is created, its id taken, and then garbage collected. Then B.__str__
is created, and happens to end up at the exact same address that A.__str__
was at earlier, so it gets (in CPython) the same id.
Try assigning A.__str__
and B.__str__
to temporary variables and you'll see something different:
>>> f = A.__str__
>>> g = B.__str__
>>> id(f) == id(g)
False
For a simpler example of this phenomenon, try:
>>> id(float('3.0')) == id(float('4.0'))
True
The following works:
>>> id(A.__str__.im_func) == id(A.__str__.im_func)
True
>>> id(B.__str__.im_func) == id(A.__str__.im_func)
False
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With