如何过滤扩展列表对象的类的返回值

2024-04-25 00:25:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个扩展list对象的类,似乎很合适,因为它是一个list,这个类还有两个布尔属性,用于过滤返回值。你知道吗

我可以填充类调用自我附加,该类将接收一个列表字典,并附加一个存储该字典内容的类的实例;该类存储一个特定类的实例列表,很像其他语言中的向量。你知道吗

下面是一个示例代码:

data = [
    { 'id': 0, 'attr1': True, 'attr2': False },
    { 'id': 1, 'attr1': False, 'attr2': True },
    { 'id': 2, 'attr1': False, 'attr2': False },
    { 'id': 3, 'attr1': True, 'attr2': True }
]

class MyClass(object):
    def __init__(self, data):
        self.id = data['id']
        self.attr1 = data['attr1']
        self.attr2 = data['attr2']

class MyList(list):
    condition1 = True
    condition2 = True

    def __init__(self, data):
        for content in data:
            self.append(MyClass(content))

这实际上是可行的,这意味着我得到了一个列表oMyClassesinstances,现在我想做的是,如果我在访问列表时将condition1的值更改为False,它应该像这样过滤结果:

my_list = MyList(data)
for item in my_list:
    print 'id', item.id, 'attr1', item.attr1, 'attr2', item.attr2
# >> id 0 attr1 True attr2 False
# >> id 1 attr1 False attr2 True
# >> id 2 attr1 False attr2 False
# >> id 3 attr1 True attr2 True

my_list.condition1 = False
# Now it should list only the instances of MyClass that has the attr1 set to False
for item in my_list:
    print 'id', item.id, 'attr1', item.attr1, 'attr2', item.attr2
# >> id 1 attr1 False attr2 True
# >> id 2 attr1 False attr2 False

我对Python还很陌生,所以我不确定自己是否能做到这一点。你知道吗


Tags: inselfidfalsetrue列表fordata
1条回答
网友
1楼 · 发布于 2024-04-25 00:25:26

您需要重写__iter__,例如:

class MyList(list):

    def __init__(self, data):
        self.condition1 = True
        self.condition2 = True
        for content in data:
            self.append(MyClass(content))

    def __iter__(self):
        return (self[i] for i in range(len(self))
                if ((self.condition1 or self[i].attr1) and
                    (self.condition2 or self[i].attr2)))

请注意,我已经将condition1作为一个实例,而不是class属性;我假设您可以使用不同的类实例,并对这些标志进行不同的设置。你知道吗

此外,您必须在MyClass上实现__eq__,以便将其用于例如my_class in my_list,并且您可以将MyClass.__init__简化为:

def __init__(self, data):
    self.__dict__.update(data)

相关问题 更多 >