Bardia Zamanian Bardia Zamanian - 14 days ago 6
Python Question

What is python list indexes explanation here?

Here is part of my code:

some_item = target_item
first_item = my_list[0]
print first_item
print some_item
print my_list.index(first_item)
print my_list.index(some_item)
print "Finished"
exit()


And here is what I get:

<models.adb.ADB object at 0x7f1ec7654b50>
<models.seb.SEB object at 0x7f1ec7654b90>
0
0
Finished


My items in
my_list
are class objects.

Could someone please explain this behavior?

Answer

It depends on the comparison implemented for ADB and SEB, probably by implementing the __eq__ operator for this classes.

When python will look for the instance of first_item and some_item on the list, he will use this operator to determine if the i-th element on the list is this element, sweeping for every i.

Therefore, if the implementation is like

class Parent:
    def __init__(self):
        self.x = 0
    def __eq__(parentObj):
        return self.x == parentObj.x

class ADB (Parent):
   def __init__(self): super.__init__()

class SEB (Parent):
   def __init__(self): super.__init__()

it would result in ADB() == SEB(), therefore, causing the objects to both "match" the first list's element when being compared to it, but being different objects at the same time.


Note that same can go for this as well, used inheritance for simplification of the example.

class ADB (Parent):
    def __init__(self):
        self.x = 0
    def __eq__(obj):
        return self.x == obj.x

class SEB (Parent):
    def __init__(self):
        self.x = 0
    def __eq__(obj):
        return self.x == obj.x
Comments