为Python类实现“and”?

2024-09-30 01:36:14 发布

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

我有类似的代码:

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)
    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)

我可以成功运行筛选测试,例如:

print list(mytable.filter(Row.val3 == 7))
# prints [[1, 2, 7, 'cat'], [7, 7, 7, 'foo']]
print list(mytable.filter(Row.val2 == 2))
# prints [[1, 2, 3, 'hello'], [1, 2, 7, 'cat'], [1, 2, 3, 'hi']]

但是,当我尝试使用and时,它并没有像我希望的那样工作:

print list(mytable.filter((Row.val3 == 7) and (Row.val2 == 2)))
# this only evaluates the second condition, instead of both conditions, printing:
# [[1, 2, 3, 'hello'], [1, 2, 7, 'cat'], [1, 2, 3, 'hi']]

如何使和正确工作?你知道吗


Tags: selfreturninitmydefoperatorclassrows
1条回答
网友
1楼 · 发布于 2024-09-30 01:36:14

不能连接到andor逻辑运算符,因为它们是short-circuit;首先计算左侧表达式,如果该表达式的结果决定结果,则永远不会计算右侧表达式。该操作返回最后计算的表达式的值。你知道吗

在您的例子中,(Row.val3 == 7) and (Row.val2 == 2)表达式首先计算(Row.val3 == 7),当它返回一个没有任何特定钩子的实例时,它就是considered a true value,因此右侧表达式的结果随后被返回。你知道吗

您可以在这里使用^{} and ^{} (bitwise AND and OR) operators,这些将委托给^{}^{}钩子。这就是像SQLAlchemy这样的ORM库所做的。你知道吗

相应的operator函数是^{}^{}。你知道吗

相关问题 更多 >

    热门问题