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?
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With