gpt4 book ai didi

python自定义类运算符重载

转载 作者:太空宇宙 更新时间:2023-11-03 13:19:45 24 4
gpt4 key购买 nike

假设我有一个类:

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

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

最佳答案

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

class Cat:

def __init__(self, name = "default", 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

关于python自定义类运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18210436/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com