簡體   English   中英

為Python類實現“和”?

[英]Implementing “and” for Python class?

我有類似這樣的代碼:

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']]

我怎樣才能正常工作?

你不能掛鈎到andor邏輯運算符,因為它們短路 ; 首先評估左手表達式,如果該表達式的結果確定結果,則永遠不會評估右手表達式。 該操作返回最后一個表達式的值。

在您的情況下, (Row.val3 == 7) and (Row.val2 == 2)表達式首先計算(Row.val3 == 7) ,因為它返回一個沒有任何特定鈎子的實例,否則,它是被認為是真值 ,因此返回右手表達式的結果。

可以使用&| (按位AND和OR)運算符在這里,它們委托給object.__and__object.__and__object.__or__鈎子。 這就像SQLAlchemy那樣的ORM庫。

相應的operator函數是operator.and_operator.or_

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM