Say I have a class in Python that has an eq method defined for comparing attributes for equality:
class Foo(object): # init code... def __eq__(self, other): # usual eq code here....
How can I then compare two instances of Foo for reference equality (that is test if they are the same instance)? If I do:
f1 = Foo() f2 = Foo() print f1 == f2
I get True even though they are different objects.
== operator is used to check whether two variables reference objects with the same value.
Every object has an identity, a type and a value. == and is are two ways to compare objects in Python. == compares 2 objects for equality, and is compares 2 objects for identity.
=== <— This is a question . It asks if the right operand is the same as the left operand. Examples: 10 === 10 <— is left 10 the same as right 10 ? .
Thats the is
operator
print f1 is f2
f1 is f2
checks if two references are to the same object. Under the hood, this compares the results of id(f1) == id(f2)
using the id
builtin function, which returns a integer that's guaranteed unique to the object (but only within the object's lifetime).
Under CPython, this integer happens to be the address of the object in memory, though the docs mention you should pretend you don't know that (since other implementation may have other methods of generating the id).
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