Python 检查对象(具有某些属性值)是否不在列表中

Python 检查对象(具有某些属性值)是否不在列表中,python,python-2.7,Python,Python 2.7,我是Python新手。我正在使用Python v2.7 我定义了一个简单的类产品: class Product: def __init__(self, price, height, width): self.price = price self.height = height self.width = width 然后,我创建了一个列表,该列表随后附加了一个Product对象: # empty list prod_list = [] #

我是Python新手。我正在使用Python v2.7

我定义了一个简单的类
产品

class Product:
    def __init__(self, price, height, width):
        self.price = price
        self.height = height
        self.width = width
然后,我创建了一个列表,该列表随后附加了一个
Product
对象:

# empty list
prod_list = []
# append a product to the list, all properties have value 3
prod1 = Product(3,3,3)
prod_list.append(prod1)
然后,我创建了另一个
Product
对象,该对象设置了相同的初始化值(全部3个):

然后,我想通过以下方式检查
prod\u list
是否包含价格为3、宽度为3、高度为3的
产品
对象:

if prod2 not in prod_list:
   print("no product in list has price=3, width=3 & height=3")

我希望没有打印出来的消息,但它是打印出来的。在Python中,如何检查列表中是否没有具有特定属性值的对象?

您需要向对象添加
相等属性。要获取对象属性,可以将属性名称传递给
operator.attrgetter
,后者返回已获取属性的元组,然后可以比较元组。您还可以使用
\uuuu dict\uuuu
属性,该属性将模块的名称空间作为字典对象提供给您。然后,您可以获取要基于属性名称比较对象的属性名称

from operator import attrgetter

class Product:
    def __init__(self, price, height, width):
        self.price = price
        self.height = height
        self.width = width

    def __eq__(self, val):
        attrs = ('width', 'price', 'height')
        return attrgetter(*attrs)(self) == attrgetter(*attrs)(val)

    def __ne__(self, val):
        attrs = ('width', 'price', 'height')
        return attrgetter(*attrs)(self) != attrgetter(*attrs)(val)
编辑:

正如@Ashwini在基于python wiki的评论中提到的:

比较运算符之间没有隐含的关系。这个
x==y的真理并不意味着
x=y
为假。因此,当 定义
\uuuu eq\uuuu()
,还应定义
\uu ne\uuuuu()
,以便 操作员将按预期操作

因此,作为一种更全面的方式,我还向对象添加了
\uuu ne\uu
属性。如果其中一个属性不等于另一个对象中的相对属性,则返回True

演示:


注意:@AshwiniChaudhary,谢谢你的评论,但是你能告诉我如何定义
\uu_une\uu()
?虽然我读过你的链接,但我对此一无所知。@Kasramvd,谢谢!虽然我已经接受了你的答案,但是你能不能也解释一下
\uuu ne\uuu()
部分代码是做什么的?@Leem.fin欢迎,刚刚添加。@Kasramvd,谢谢!看起来
\uu ne\uuu()
代码中有输入错误,您错过了
attrs
getter
之间的
,此外,您应该将
attr
更改为
attrs
from operator import attrgetter

class Product:
    def __init__(self, price, height, width):
        self.price = price
        self.height = height
        self.width = width

    def __eq__(self, val):
        attrs = ('width', 'price', 'height')
        return attrgetter(*attrs)(self) == attrgetter(*attrs)(val)

    def __ne__(self, val):
        attrs = ('width', 'price', 'height')
        return attrgetter(*attrs)(self) != attrgetter(*attrs)(val)
prod_list = []
prod1 = Product(3, 3, 3)
prod_list.append(prod1)

prod2 = Product(3, 3, 2)
prod_list.append(prod2)

prod3 = Product(3, 3, 3)
print prod3 in prod_list
True 
prod3 = Product(3, 3, 5)
print prod3 in prod_list
False