首页 > 解决方案 > 如何确定两个列表在 python 中是否具有相同的属性?

问题描述

对于我的编码项目,我必须使用此代码并查看是否有任何类似的属性。如果是,我需要一个打印语句说“列表具有相似的属性”,如果不是,那么应该有一个打印语句说“两个语句具有相同的属性”。

class Box:
    def __init__(self, date1, contents1, location1):
        self.date = date1
        self.contents = contents1
        self.location = location1


box23 = Box("2016", "medical records", "storage closet")
box21 = Box("2018", "lotion samples", "waiting room")
box07 = Box("2020", "flyers for flu shot", "receptionist desk")
print(box23.date)
print(box21.contents)
print(box07.location)

标签: python

解决方案


如果要比较单个属性,可以使用

if box23.date == box21.date:
    print("boxes have the same date")
else:
    print("boxes have different dates")

如果要比较所有属性,可以简单地比较__dict__属性:

if box23.__dict__ == box21.__dict__:
    print("boxes have the same attributes")
else:
    print("boxes don't have the same attributes")

推荐阅读