zoukankan      html  css  js  c++  java
  • 富比较方法

    以下方法统称为富比较方法:

    __eq__(self, other)

    使用==比较两个对象时会触发内部代码执行。

    class A:
        def __eq__(self, other):
            print('触发A内方法的执行')
            if self.name == other.name:  # 自己定制比较规则。
                return True
            return False
    
    class B:
        def __eq__(self, other):
            print('触发B内方法的执行')
            if self.name == other.name:
                return True
            return False
    
    a = A()
    a.name = 'libai'
    b = B()
    b.name = 'dufu'
    
    print(a == b)
    print(b == a)
    
    触发A内方法的执行
    False
    触发B内方法的执行
    False
    

    除了__eq__还有其他的比较方法:

    object.__lt__(self, other):使用<比较触发。

    object.__le__(self, other):使用<=比较触发。

    object.__ne__(self, other):使用!=比较触发。

    object.__gt__(self, other):使用>比较触发。

    object.__ge__(self, other):使用>=比较触发。


  • 相关阅读:
    第七单元
    第六单元
    第五单元
    第四单元
    第三章
    第二单元
    第一单元
    单词
    机器学习和模式识别的区别
    TODO-项目
  • 原文地址:https://www.cnblogs.com/ChiRou/p/14238036.html
Copyright © 2011-2022 走看看