“如何定义”;在;对于python类
如果我有一个包含字符串字段的python类列表,是否有一种方法可以使用中的“如何定义”;在;对于python类,python,python-3.x,class,compare,Python,Python 3.x,Class,Compare,如果我有一个包含字符串字段的python类列表,是否有一种方法可以使用中的将字符串与该类的对象列表进行比较?我很好奇是否有这样的方法: class Foo: def __init__(self, s): self.s = s bar = Foo('test') ls = [bar] if 'test' in ls: print("Yay!") 通过修改\uuuuu eq\uuuu方法,或者甚至可能在和其他条件检查。 演示: 您关于定义自定义\uuuuu eq
将字符串与该类的对象列表进行比较?我很好奇是否有这样的方法:
class Foo:
def __init__(self, s):
self.s = s
bar = Foo('test')
ls = [bar]
if 'test' in ls:
print("Yay!")
通过修改\uuuuu eq\uuuu
方法,或者甚至可能在
方法中有一个\uu,我不知道你关于修改\uuuueq\uu
的猜测是正确的。这绝对是一种方法。您只需使用对象的相应属性检查\uuuuuuueq\uuuuu
参数的值。因此,作为一种非常简单的方法,您可以实现如下内容:
In [1]: class Foo:
...: def __init__(self, s):
...: self.s = s
...:
...: def __eq__(self, value):
...: return self.s == value
...:
In [2]: bar = Foo('test')
...: ls = [bar]
...:
In [3]: 'test' in ls
Out[3]: True
请注意,此\uuuuuuueq\uuuuu
方法没有任何限制,例如类型检查或其他一些错误处理。如果你认为在你的案例中需要它们,你可以考虑使用<代码>尝试EXCEP < /C>和其他条件检查。
演示:
您关于定义自定义\uuuuu eq\uuuu
的直觉是正确的。您可以实现以下目标,这似乎是您的目标:
>>> class Foo:
... def __init__(self, s):
... self.s = s
... def __eq__(self, other):
... if isinstance(other, Foo):
... return self.s == other.s
... else:
... return self.s == other
...
>>>
>>> bar = Foo('bar')
>>> l = [bar]
>>> bar in l
True
>>> 'bar' in l
True
>>> Foo('baz') in l
False
>>> 'baz' in l
False
我还想指出,有一种方法允许您定义成员身份操作符的行为(
中的)。但是,这是容器类型上的一个方法,因此在这里为类Foo
定义此方法不会有任何作用,因为中的应用于列表,而不是其单个项。isinstance()方法在这里很关键,我不知道您可以做到这一点!我的班级现在工作如梦,很高兴能帮忙!请注意,isinstance(bar,Foo)
比bar更健壮。\uuuu class\uuu==Foo
,因为它也适用于Foo
的子类。我不认为是否需要使用isinstance(bar,Foo)
因为一旦等式一侧的等式检查失败,Python将调用另一侧的\uuuuuueq\uuuuu
。
>>> class Foo:
... def __init__(self, s):
... self.s = s
... def __eq__(self, other):
... if isinstance(other, Foo):
... return self.s == other.s
... else:
... return self.s == other
...
>>>
>>> bar = Foo('bar')
>>> l = [bar]
>>> bar in l
True
>>> 'bar' in l
True
>>> Foo('baz') in l
False
>>> 'baz' in l
False