设为首页 加入收藏

TOP

python魔法方法-比较相关(二)
2017-09-30 16:47:40 】 浏览:5111
Tags:python 魔法 方法 比较 相关
word):
return str.__new__(cls, word) def __eq__(self, other): if ('scolia' in self ) and ('scolia' in other): return True else: return False a = Foo('scolia') b = Foo('scolia123') print a == b

  所以,这些魔法方法其实就是重载了相应的符号而已,例如这里的 == ,左边的相当于 self,右边的相当于 other。你可以根据自己的需要进行逻辑编排。

又例如:

class Foo(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)

 

  这里重载了多个比较符,是核心是按照字符串的长度进行比较,越长的越大。这里看似返回的是一个表达式,但是函数在真正返回的时候会将这个表达式计算出来,也就是说最终返回的其实还是布尔值。

  而没有重载的比较符,如这里没有重载 __eq__ 即 == ,将自动调用其父类的方法,这也很符合我们继承的概念。

如果和基本类型比较呢:

class Foo(str):
    def __new__(cls, word):
        return str.__new__(cls, word)

    def __eq__(self, other):
        if ('scolia' in self ) and ('scolia' in other):
            return True
        else:
            return False

b = Foo('scolia')
a = 'scolia123'
print a == b
print b == a

  貌似是以我们自己写的方法为准,不管 == 两边的顺序如何。

如果两个自定义的类冲突呢:

class Foo(str):
    def __new__(cls, word):
        return str.__new__(cls, word)

    def __eq__(self, other):
        if ('scolia' in self ) and ('scolia' in other):
            return True
        else:
            return False

class Boo(str):
    def __new__(cls, word):
        return str.__new__(cls, word)

    def __eq__(self, other):
        if ('scolia' in self ) and ('scolia' in other):
            return False
        else:
            return True


a = Foo('scolia')
b = Boo('scolia')
print a == b
print b == a

  此时,谁在 == 号的左边,就运用谁的规则。

 


 

  关于比较的魔法方法就讨论到这里,欢迎大家交流。

  相关的参考资料:戳这里 

 

首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇python字符串方法的简单使用 下一篇Linux 环境下自动化测试工具,Red..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目