Sorting class instances in python

前端 未结 3 1645
深忆病人
深忆病人 2021-01-15 17:31

What does python 2.7 use to sort vanilla class instances? I\'m interested in the default sorting behavior.

Suppose I have the class

class S():
    pa         


        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-15 17:45

    I tried your example on my own machine (python 2.7):

    >>> sorted(l)
    [(<__main__.S instance at 0x107142a70>, 'a'), (<__main__.S instance at 0x107142ab8>, 'b'), (<__main__.S instance at 0x107142b00>, 'c')]
    

    Note that the sorted list is in order of the id():

    >>> id(a)
    4413729392
    >>> id(b)
    4413729464
    >>> id(c)
    4413729536
    

    If I generate the hashes I get:

    >>> hash(a)
    275858087
    >>> hash(b)
    -9223372036578917717
    >>> hash(c)
    275858096
    

    Which suggests that the sorting is not based on the hash.

    See derekerdmann's answer for information on how to make python sort your class the way you want.

    Edit: By the way, if you put the items in the list in reverse and then sort it, you get:

    >>> l = [(c,'c'), (b, 'b'), (a, 'a')]
    >>> sorted(l)
    [(<__main__.S instance at 0x107142a70>, 'a'), (<__main__.S instance at 0x107142ab8>, 'b'), (<__main__.S instance at 0x107142b00>, 'c')]
    

    Once again, its sorted in order of the id().

提交回复
热议问题