【发布时间】:2013-08-15 03:33:51
【问题描述】:
假设我有一堂课:
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
我需要重载哪个运算符才能identify 类 Cat by 的成员变量 name 的对象?
【问题讨论】:
-
我猜它是相等运算符,您可以在其中检查另一个对象是否属于同一实例,并且它的 name 属性与当前对象的名称匹配:
__eq__(self, other): #todo check if other is ame type and if name matches self.name定义相等运算符的行为,== .抱歉,我是 C# 人...
标签: python class oop operator-overloading