美文网首页
实现对象的比较

实现对象的比较

作者: noteby | 来源:发表于2019-02-21 09:38 被阅读0次
    import functools
    
    
    class WordTest(str):
    
        def __new__(cls, word):
            return str.__new__(cls, word)
    
        def __gt__(self, other):
            return len(self) > len(other)
    
        def __lt__(self, other):
            return len(self) < len(other)
    
        def __ge__(self, other):
            return len(self) >= len(other)
    
        def __le__(self, other):
            return len(self) <= len(other)
    
        def __eq__(self, other):
            return len(self) == len(other)
    
    
    @functools.total_ordering  # __eq__ and __gt__( or __lt__)
    class Word(str):
    
        def __new__(cls, word):
            return str.__new__(cls, word)
    
        def __gt__(self, other):
            return len(self) > len(other)
    
        def __eq__(self, other):
            return len(self) == len(other)
    
    
    s1 = Word('ball')
    s2 = Word('b')
    print(s1 > s2)
    
    True
    

    相关文章

      网友评论

          本文标题:实现对象的比较

          本文链接:https://www.haomeiwen.com/subject/mlwlyqtx.html