I've got an interesting question that I do not understand at all why this is happening. So, I'm trying to sort a list of tuples, where the first element of tuple is an object, based on the attributes within the said objects. So, I have created the following code to test this functionality:
class s(object):
def __init__(self, name):
self._name = name
def get_name(self):
return self._name
def val(x):
#This used in place of a lambda
return x[0]._name
e1 = s("Fred")
e2 = s("Bill")
print(e2.get_name())
list1 = [(e1, 3), (e2, 4)]
for n in list1:
print(val(n))
list2 = sorted(list1, key = val)
print(list2)
print(list2[0] == e2)
print(e2.get_name)
print(e2._name)
With the output of this being:
Bill
Fred
Bill
[(<__main__.s object at 0x0000002AC47D6438>, 4), (<__main__.s object at 0x0000002AC47D6240>, 3)]
False
<bound method s.get_name of <__main__.s object at 0x0000002AC47D6438>>
Bill
I have absolutely no clue why I'm getting the memory addresses of the attributes as the first elements of my tuples after sorting, and I've scoured through SO and there really shouldn't be any issue with this code since it looks exactly the same as alot of other posts on this. Can ANYONE please help me out here and point out why this is happening? I expect this output:
print(list2) #After sorting
OUTPUT:
[(e2, 4), (e1, 3)]