以下是一个示例代码,该代码演示了如何比较包含标签的类别。
class Category:
def __init__(self, name, tags):
self.name = name
self.tags = tags
def compare(self, other_category):
common_tags = set(self.tags) & set(other_category.tags)
if len(common_tags) > 0:
print(f"Categories {self.name} and {other_category.name} have common tags: {common_tags}")
else:
print(f"Categories {self.name} and {other_category.name} do not have any common tags.")
# 创建两个类别对象
category1 = Category("Category 1", ["tag1", "tag2", "tag3"])
category2 = Category("Category 2", ["tag2", "tag3", "tag4"])
# 比较两个类别对象
category1.compare(category2)
在上述代码中,我们定义了一个名为Category
的类,它具有name
和tags
属性。name
属性表示类别的名称,tags
属性是一个包含与类别相关的标签的列表。
这个类还有一个compare
方法,该方法接受另一个Category
对象作为参数。在compare
方法中,我们使用set
数据类型来找到两个类别对象的共同标签。如果两个类别有共同的标签,则打印出这些共同标签。如果两个类别没有共同的标签,则打印出它们没有共同标签的消息。
在示例代码的最后,我们创建了两个Category
对象,并将它们命名为category1
和category2
。然后,我们调用category1
的compare
方法,并将category2
作为参数传递给它。这样,我们可以比较两个类别对象并输出它们的共同标签。