如何将Python中的list与中使用imlicator的某个类进行比较?

2024-04-20 09:44:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我想比较包含在中使用隐式的某些类的列表。代码如下:

class Word:
    def __init__(self, p_name):
        self.name = p_name
    def __eq__(self, other):
        return self.name == other.name
    def __str__(self):
        return "_name_: " + self.name
t1 = []
t1.append(Word("John"))     
t2 = []
t2.append(Word("John"))
if t1 in t2:
    print("the same")

我得到一个错误,“列表没有属性'name'”。我知道我可以编写一些循环,但如果在这种情况下可能的话,我想在中使用隐式


Tags: 代码nameself列表returninitdefjohn
1条回答
网友
1楼 · 发布于 2024-04-20 09:44:48

这:

if t1 in t2:
    print("the same")

应为以下各项之一:

# Check if a single word is in t2.
w = Word("John")
if w in t2:
    print("the same")

# Check if any element of t1 is in t2.
if any(w in t2 for w in t1):
    print("the same")

# Check if all elements of t1 are in t2.
if all(w in t2 for w in t1):
    print("the same")

您不应该检查一个列表是否在另一个列表中。您可以检查某个特定项目是否在列表中,也可以将t1中的所有项目与t2中的项目进行比较

def __eq__(self, other):
    return isinstance(other, Word) and self.name == other.name

__eq__中添加一个检查other是否为Word也是一个好主意。您的代码崩溃是因为other是一个列表而不是Word,因此other.name查找失败

相关问题 更多 >