为 Python class 实施 __contains__ (in) 时出错

Error implementing __contains__ (in) for a Python class

我正在尝试实现包含,以便它可以用于我的 python 对象中的多个属性中的任何一个。我能够成功实现“==”和大多数其他比较运算符,但是 "in" 给我带来了问题:

import operator
class Comparator:
     def __init__(self,fieldName,compareToValue,my_operator):
         self.op = my_operator
         self.field = fieldName
         self.comparedTo = compareToValue
     def __call__(self,row):
         my_row_val = getattr(row,self.field)
         return self.op(my_row_val,self.comparedTo)


class Row:
    class RowItem:
         def __init__(self,name):
              self.name = name
         def __eq__(self,other):
             return Comparator(self.name,other,operator.eq)
         def __contains__(self,other):
             return Comparator(self.name,other,operator.contains)
    val1 = RowItem("val1")
    val2 = RowItem("val2")
    val3 = RowItem("val3")
    val4 = RowItem("val4")
    def __init__(self, val1, val2, val3, val4):
        self.val1 = val1
        self.val2 = val2
        self.val3 = val3
        self.val4 = val4
    def __str__(self):
        return str([self.val1,self.val2,self.val3,self.val4])
    def __repr__(self):
        return str(self)


class MyTable:
    def __init__(self,rows):
        self.rows = rows
    def filter(self,condition):
        for row in self.rows:
            if condition(row):
               yield row

rows = [Row(1,2,3,"hello"),Row(1,2,7,"cat"),Row(1,2,3,"hi"),Row(7,7,7,"foo")]
mytable = MyTable(rows)

# the line below works fine!
print list(mytable.filter(Row.val3 == 7))

# this line below does not work
print list(mytable.filter("h" in Row.val4))
# TypeError: 'bool' object is not callable

# this line also does not work
print list(mytable.filter(Row.val4 in "hello world"))
# TypeError: 'in <string>' requires string as left operand, not instance
  1. 对于 filter 你必须传递一个可调用对象,而不是布尔值
  2. row_obj.val4 是 class RowItem 的实例,而不是 string [=21] 的 __contains__ 方法所期望的字符串=]

感谢凯文在评论中回答这个问题。问题在于 in__contains__() 方法)将结果强制转换为布尔值,这与其他逻辑比较运算符(__lt__()__eq__() 等)不同。

这似乎主要是因为向后兼容。 更多信息在这里: https://mail.python.org/pipermail/python-dev/2013-July/127297.html

解决此问题的一种方法是创建一个新方法(例如,contains_):

尝试这样的事情(这是一个不好的例子,因为 contains 可以在这段代码中工作:

import operator
class Comparator:
     def __init__(self,fieldName,compareToValue,my_operator):
         self.op = my_operator
         self.field = fieldName
         self.comparedTo = compareToValue
     def __call__(self,row):
         my_row_val = getattr(row,self.field)
         return self.op(my_row_val,self.comparedTo)


class Row:
    class RowItem:
         def __init__(self,name):
              self.name = name
         def __eq__(self,other):
             return Comparator(self.name,other,operator.eq)
         def contains_(self,other):
             return Comparator(self.name,other,operator.contains)
    val1 = RowItem("val1")
    val2 = RowItem("val2")
    val3 = RowItem("val3")
    val4 = RowItem("val4")
    def __init__(self, val1, val2, val3, val4):
        self.val1 = val1
        self.val2 = val2
        self.val3 = val3
        self.val4 = val4
    def __str__(self):
        return str([self.val1,self.val2,self.val3,self.val4])
    def __repr__(self):
        return str(self)

而不是:

         def __contains__(self,other):
             return Comparator(self.name,other,operator.contains)

当然,在尝试执行 "in" 时,您需要执行以下操作:

print list(mytable.filter(Row.val4.contains_("h"))) #new way to call in (__contains__)

而不是:

print list(mytable.filter(Row.val4.__contains__("h"))) #old broken way to call in (__contains__)