为了简化我的代码,我想实现一个包含所有内容的集合.我认为解决这个问题的最简单方法是使用一个自定义集,为任何查询返回True.在我的特定情况下,我最感兴趣的是集合的交叉,以便满足以下条件:
u_set = UniversalSet()
u_set & {1, 2, 3} == {1, 2, 3} # (1)
{1, 2, 3} & u_set == {1, 2, 3} # (2)
Run Code Online (Sandbox Code Playgroud)
我UniversalSet按以下方式进行了子类化:
class UniversalSet(set):
def __and__(self, other):
return other
Run Code Online (Sandbox Code Playgroud)
这适用于__intersect__,但set仍然失败.是否有同样简单的(1)工作方式?
您还需要定义和operator()的反转版本,__rand__以便在第二个参数和第一个参数时调用子类方法.
class UniversalSet(set):
def __and__(self, other):
return other
def __rand__(self, other):
return other
Run Code Online (Sandbox Code Playgroud)