实现对象的比较

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
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容