Python对象进行大小对比,重写__gt__、__eq__等方法

本文介绍了重写重写__gt__、__eq__等对象内置方法。
比较不同花色的扑克牌,按黑红梅方顺序从大到小比较,相同花色比较数值大小。

#!/usr/bin/env python
# encoding: utf-8
"""
@author: 
@license: (C) Copyright 2013-2017, Node Supply Chain Manager Corporation Limited.
@contact: 
@software: pycharm
@file: 8.8.py
@time: 2019/2/16 12:23
@desc:
"""

flowers = ('♦', '♣', '♥', '♠')
values = ('2', '3', '4', '5',
          '6', '7', '8', '9',
          '10', 'J', 'Q', 'K', 'A')


class Card(object):
    def __init__(self, flower, value):
        self.flower = flower
        self.value = value

    def __gt__(self, other):
        if not isinstance(other, Card):
            raise TypeError('>运算对象是Card')
        if flowers.index(self.flower) > flowers.index(other.flower):
            return True
        elif flowers.index(self.flower) == flowers.index(other.flower) and \
            values.index(self.value) > values.index(other.value):
            return True
        else:
            return False


    def __eq__(self, other):
        if not isinstance(other, Card):
            raise TypeError('=运算要求目标是Card')
        if values.index(self.value) == values.index(other.value) and \
                flowers.index(self.flower) == flowers.index(other.flower):
            return True
        else:
            return False

    def __ge__(self, other):
        if not isinstance(other, Card):
            raise TypeError('>=运算要求目标是Card')
        return self > other or self == other

    def __repr__(self):
        return '%s-%s' % (self.flower, self.value)


if __name__ == "__main__":
    cd1 = Card(flower="♠", value="A")
    cd2 = Card(flower="♠", value="K")
    cd3 = Card(flower="♥", value="K")
    cd4 = Card(flower="♥", value="J")
    cd5 = Card(flower="♥", value="K")
    print(cd1 > cd2)  # True
    print(cd1 < cd2)  # False
    print(cd2 < cd3)  # False
    print(cd2 > cd3)  # True
    print(cd3 == cd5)  # True
    print(cd3 < cd5)  # False
    print(cd3 > cd5)  # False
    print(cd3 >= cd5)  # True
    print(cd3 <= cd5)  # True
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值