加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python自定义类运算符重载

发布时间:2020-12-20 11:28:59 所属栏目:Python 来源:网络整理
导读:假设我有一个班级: class Cat: def __init__(self,name = "default",age = 0): self.name = name self.age = age 我还有一个猫列表: l = [Cat('Joe')] 现在我不能打电话给以下人员: if 'Joe' in l: # the right syntax would be if Cat('Joe') in list 我
假设我有一个班级:

class Cat:
    def __init__(self,name = "default",age = 0):
        self.name = name
        self.age = age

我还有一个猫列表:

l = [Cat('Joe')]

现在我不能打电话给以下人员:

if 'Joe' in l: # the right syntax would be if Cat('Joe') in list

我需要重载哪个运算符才能通过其成员变量名识别类Cat的对象?

解决方法

您必须定义__eq__方法,如下所示:

class Cat:

    def __init__(self,age = 0):
        self.name = name
        self.age = age

    def __eq__(self,other):
        if isinstance(other,str):
            return self.name == other
        elif isinstance(other,Cat):
            return self.name == other.name

这样当你运行支票时:

l = [Cat('Joe')]

'Joe' in l
#True

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读