20比较类的一种内在逻辑

我们平时会直接在idle里面去写类似于

10>6,但是其实仔细思考一下,10和6是int的实例对象,感觉学逻辑真的比单纯学代码有用,参照之前的那个图,多去想一下逻辑其实真的很好!

python3其实是这样不支持的~(所以会报错)

class A:
    pass
a2 = A()
a1 = A()
print (a1 > a2)

这样其实就是一个正确的比较(会正常的输出false)

class Person:
    def __init__(self,age,height):
        self.age = age
        self.height = height
    # == != >= < <=
    def __eq__(self, other):
        print(other)
        return self.age == other.age
    pass
p1 = Person(19,100)
p2 = Person(18,190)
print(p1 == p2)

其余的一些比较方法

class Person:
    def __init__(self,age,height):
        self.age = age
        self.height = height
    # == != >= < <=
    def __eq__(self, other):
        print(other)
        return self.age == other.age
    pass
    def __ne__(self, other):
        print('***')
    def __ge__(self,other):
        pass
    def __it__(self,other):
        pass 



p1 = Person(19,100)
p2 = Person(18,190)
print(p1 != p2)

我感觉写的多了和听课听的多了,自己就已经会去思考内部的一些逻辑和思考一些事情了,比如这个

import functools
@functools.total_ordering
class Person:
    def __lt__(self,other):
        #pass
        print('lt')
    def __eq__(self,other):
        # pass
        print('eq')
    def __le__(self,other):
        print('le')
p1 =Person()
p2 = Person()
print(p1 <=p2)
print(Person.__dict__)

20比较类的一种内在逻辑_第1张图片分析一下哦~最后比较的是p1<=p2。我在原始定义的时候如果定义了≤也就是__le__那么之前如果定义了<+=那么之前的就失效了,但是如果没有<=,拥有他的相反即>=那么,就不成立,只能单独运行前面的<和=

20比较类的一种内在逻辑_第2张图片但是字典属性里,无论什么时候都会有小于等于和大于等于

你可能感兴趣的:(python,开发语言)