为Python类实现“和”?

时间:2015-05-07 16:28:31

标签: python class hook logical-operators

我的代码类似于:

long ms = 86400000;

long s = ms % 60;
long m = (ms / 60) % 60;
long h = (ms / (60 * 60)) % 24;
String timeFind = String.format("%d:%02d:%02d", h, m, s);

我可以成功运行过滤测试,例如:

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

我如何才能正常工作?

1 个答案:

答案 0 :(得分:3)

您无法挂钩andor逻辑运算符,因为它们short-circuit;首先评估左手表达式,如果该表达式的结果确定结果,则永远不会评估右手表达式。该操作返回最后一个表达式的值。

在你的情况下,(Row.val3 == 7) and (Row.val2 == 2)表达式首先评估(Row.val3 == 7),因为它返回一个没有任何特定钩子的实例,否则它是considered a true value,所以右边的结果然后返回-hand表达式。

可以在这里使用& and | (bitwise AND and OR) operators,这些委托给object.__and__object.__or__个钩子。这就像SQLAlchemy那样的ORM库。

相应的operator函数为operator.and_operator.or_