Question
In python 2.7, I want to create a custom list that extends the python list by prefilling it with some static elements. I also want to extent the python list by adding some custom methods (i.e. filtering, re-initialization, etc...).
For example:
my_list = FitFuctionsList()
should give me a list already filled with some fixed elements.
I tried to inherit from the python list
:
class FitFuctionsList(list):
def __init__(self):
list.__init__(['some', 'fixed', 'list'])
but the initialization fails (an empty list is returned).
Suggestions on alternative approaches are also welcome.
Solution summary
nachshon provided a working solution even though he does not explain why it works (and why the previous example did not):
class FitFuctionsList(list):
def __init__(self):
super(FitFuctionsList, self).__init__(['some', 'fixed', 'list'])
If the need is only to initialize a list with fixed values (no custom methods), Claudiu provided a clever way of using an helper function with an attribute to initialize the list. This methods is elegant and robust since it avoids using globals:
def FitFuctionsList():
return list(FitFuctionsList.prefilled_elements)
FitFuctionsList.prefilled_elements = ["a", "b", "rofl"]