在sqlalchemy中,可以这样做:

mytable.query.filter(mytable.some_col < 5).all()

如何实现类似的功能我希望开发人员用户能够将逻辑操作传递给函数。下面是一个例子:
class row_obj:
    def __init__(self, val1, val2, val3, val4):
        self.val1 = val1
        self.val2 = val2
        self.val3 = val3
        self.val4 = val4
    def __repr__(self):
        return str(self.val1)+","+str(self.val2)+","+str(self.val3)+","+str(self.val4)

class table_obj:
    """ takes a list of row_objs """
    def __init__(self, rows):
        self.rows = rows #rows is a list of row_obj
    def __repr__(self):
        return "\n".join([str(row) for row in self.rows])
    def filter(self, condition):
        # I would like to return all rows which meet the condition here
        return table_obj([row for row in self.rows if condition])

a = table_obj([ row_obj(1,2,3,4),
      row_obj(5,6,7,8),
      row_obj(2,4,6,8),
      row_obj(5,2,7,4)])

print a.filter(row_obj.val3 == 7)
#should return
#5,6,7,8
#5,2,7,4

最佳答案

不幸的是,这有点不简单,实现起来有点粗糙,但是您可以这样做

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_obj:
    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_obj(1,2,3,4),row_obj(1,2,7,4),row_obj(1,2,3,4),row_obj(7,7,7,7)]
mytable = MyTable(rows)
print list(mytable.filter(row_obj.val3 == 7))

这不仅仅是给你一个想法,你将不得不采取的道路,将是非琐碎(和有点恶心…)

08-19 09:33