class MyClass:
def __init__(self, value):
self.value = value
def __eq__(self, other):
if isinstance(other, MyClass):
return self.value.lower() == other.value.lower()
return False
代码关键部分解释
__init__
方法:这是类的构造函数,用于初始化实例的value
属性。当创建MyClass
的实例时,会传入一个字符串值,这个值会被赋给self.value
。
__eq__
方法:这是Python的魔法方法,用于定义相等比较(==
操作符)的行为。
isinstance(other, MyClass)
:首先检查other
是否是MyClass
类的实例。如果不是,直接返回False
,因为只有同类实例之间才进行这种特定的比较。
self.value.lower() == other.value.lower()
:如果other
是MyClass
类的实例,将两个实例的value
属性都转换为小写形式,然后进行比较。如果转换为小写后的值相等,则返回True
,否则返回False
。