Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use list comprehension in list derived class

I have a list derived class and want to assign its contents using list comprehension This is the sample code:

class MyList(list):
    def __init__(self, some_data):
        self = [Foo(x) for x in some_data]

    def customFilter(self):
        self = [x for x in self if x.Selected]

Of course this does not work because the assignment to self just creates a local variable. Is there a pythonic way to achieve this without using for loop?

like image 209
JuliusG Avatar asked Sep 06 '25 03:09

JuliusG


1 Answers

It's probably better to use Collections.UserList, which is made for subclassing. It gives you a data property which holds the lists contents and avoids the problem of assigning to self:

from collections import UserList

def Foo(c):
    return c * 2

class MyList(UserList):
    def __init__(self, some_data):
        self.data = [Foo(x) for x in some_data]

MyList([1, 2, 3])
# [2, 4, 6]
like image 174
Mark Avatar answered Sep 07 '25 19:09

Mark