Python 用闭包实例化新对象

Python 用闭包实例化新对象,python,closures,Python,Closures,我正在努力理解我所做的是否合理/是否是一个好的模式 Filter是一个可调用的类,用于过滤其他类(Dataview),并在调用时返回一个新的、已过滤的Dataview对象 当然,过滤器中有一个属性,它是特定过滤器的实际函数(Filter.funct) 我希望能够创建这样的过滤器: filterc = filterb&filtera 在我的过滤器类中有以下代码: def __and__(self, other): assert isinstance(other, Filter),

我正在努力理解我所做的是否合理/是否是一个好的模式

Filter是一个可调用的类,用于过滤其他类(Dataview),并在调用时返回一个新的、已过滤的Dataview对象

当然,过滤器中有一个属性,它是特定过滤器的实际函数(Filter.funct)

我希望能够创建这样的过滤器:

filterc = filterb&filtera
在我的过滤器类中有以下代码:

def __and__(self, other):
    assert isinstance(other, Filter),"And(Logical operation) between Filters supports only another Filter,got {}".format(type(other))
    def new_funct(dataview):
        return self(dataview)&other(dataview)
    return Filter(funct=new_funct,str_representation=repr(self)+'&'+repr(other))
如您所见,我正在创建一个新的Filter对象,带有一些我正在创建的内部函数,希望它是一个闭包(例如,在某种意义上它的环境被保存)


当代码本身运行时,我想知道这是否有意义&我是否做了一些固有的错误。

这种方法没有错:它避免了为每种“复合”
过滤器创建单独的类。然而,人们可能会期望一个lambda:

return Filter(lambda x: self(x)&other(x),…)
这只是语法:它以
self
other
两种方式结束