Search code examples
pythonpython-3.xinstanceinstance-variables

How to compare two instances in Python?


Is there possibility to compare two 'instances'? I have one variable and one list. Variable have type 'instance', items in list have also the same type. When I compare variable with the same item in list:

cities = [USA, Poland, England, GB, Italy]
variable = Italy

variable == cities[-1]

I received 'False' as output. I'm 100% sure that both elements are the same.

Thanks in advance!


Solution

  • There are two types of objects in Python. Mutable, and immutable.

    Immutable

    • State cannot be changed.
    • Usually thought of as "primitive" types.
    • int, float, string, tuple, etc.

    Mutable

    • State can be updated and changed.
    • list, dict, set, bytearray, any object that is created via the class token.

    Depending on the type that you are discussing when you say variable this will affect the operator ==. Immutable types will always be checked against the actual value (e.g. 1 == 1 is True), where mutable types are checked against the object's __eq__ method (which overloads the == sign).

    All of the mutable types listed - except new objects initialized with class - have a built-in __eq__ methods that are used when the == sign is present. Assuming you are using your own object, take the following for example:

    class Obj:
        def __init__(self, integer):
            self.integer = integer
    
    print(Obj(1) == Obj(1)) # False
    

    Notice that despite integer being equal for each Obj, due to the fact Obj is a mutable type without the __eq__ method Python will check if the objects are equal to each other based on their space in memory- in other words, for it to be True, the object must be the exact same one you initialized.

    class Obj:
        def __init__(self, integer):
            self.integer = integer
    
    obj = Obj(1)
    
    print(obj == obj)  # True
    

    To manually overload the == sign, you must use the __eq__ method:

    class Obj:
        def __init__(self, integer):
            self.integer = integer
    
        def __eq__(self, other):
            # Comparison of two integers.
            return self.integer == other.integer
    
    print(Obj(1) == Obj(1))  # True