如何让类支持比较操作

高级编程技巧 学习笔记

一、让类支持比较操作


        有时我们希望自定义类的实例间可以使用,<、<=、>、>=、==、!= 符号进行比较,我们自定义比较的类,例如,有一个矩形的类,比较两个矩形的实例时,比较的是他们的面积。

  • int 类型比较的是 大小

  • str 类型比较的是 ask 码(一个一个比较)

  • 集合类型比较的是 包含关系

1.1、在类中定义 __lt__ 和 __eq__ 方法

import math

class Rect():
    def __init__(self, w, h):
        self.w = w
        self.h = h

    def area(self):
        return self.w * self.h

    # lt 是小于, ge 是大于
    def __lt__(self, other):
        return self.area() < other.area()

    # eq 是等于
    def __eq__(self, other):
        return self.area() == other.area()


class Cirle():
    def __init__(self, r):
        self.r = r

    def area(self):
        return self.r ** 2*math.pi

    def __lt__(self, other):
        return self.area() < other.area()

    def __eq__(self, other):
        return self.area() == other.area()


r1 = Rect(1, 2)
c1 = Cirle(2)
print(r1 < c1)
print(r1 <= c1)						# 报错

存在问题,不能进行 >=, ==, <= 的比较。


1.2、引入库 functools

import math
from functools import total_ordering

@total_ordering
class Rect():
    def __init__(self, w, h):
        self.w = w
        self.h = h

    def area(self):
        return self.w * self.h

    # lt 是小于, ge 是大于
    def __lt__(self, other):
        return self.area() < other.area()

    # eq 是等于
    def __eq__(self, other):
        return self.area() == other.area()


class Cirle():
    def __init__(self, r):
        self.r = r

    def area(self):
        return self.r ** 2*math.pi

    def __lt__(self, other):
        return self.area() < other.area()

    def __eq__(self, other):
        return self.area() == other.area()


r1 = Rect(1, 2)
r2 = Rect(2, 1)
c1 = Cirle(2)
print(r1 < c1)
print(r1 <= c1)
print(r1 == r2)

存在问题,代码冗余。


1.3、使用 abc 模块,创建抽象基类

import math
from functools import total_ordering
import abc

@total_ordering
class Shape(metaclass=abc.ABCMeta):
    @abc.abstractmethod
    def area(self, key):
        pass

    def __lt__(self, other):
        return self.area() < other.area()

    def __eq__(self, other):
        return self.area() == other.area()


class Rect(Shape):
    def __init__(self, w, h):
        self.w = w
        self.h = h

    def area(self):
        return self.w * self.h


class Cirle(Shape):
    def __init__(self, r):
        self.r = r

    def area(self):
        return self.r ** 2*math.pi


r1 = Rect(1, 2)
r2 = Rect(2, 1)
c1 = Cirle(2)
print(r1 < c1)
print(r1 >= c1)
print(r1 == r2)
发布了85 篇原创文章 · 获赞 0 · 访问量 1231

猜你喜欢

转载自blog.csdn.net/qq_43621629/article/details/104077978