mercredi 27 octobre 2021

Is it 'worth' subclassing a python class to change the initialiser, or are there better patterns to use?

I'm designing a library with a fairly powerful class - we can think of it as a list.

I'm expecting users to want to create their own lists, prepopulated with certain content. For the sake of example, things like "add n identical items to the list", or "initialise with the numbers from a->b". Note that these things don't really change how the list works, they just set it up in some complex way.

The users will need to use these from different bits of code, be able to reuse them in the future.

I can see two possible ways for the users to do this:

Create a function which builds the object for them, e.g.:

def make_item_list(n,x):
    ls = [x]
    ls *= n
    return ls

Or, alternatively, subclass the list to add an initialiser:

def RepeatList(List):
    def __init__(self,n,x):
        super().__init__()
        self.listitems = [x]*n

Clearly this is a toy example but which of these is more sensible and 'pythonic'? If there are other patterns in Python to do this, what are they? If the choice of pattern depends on something else I haven't mentioned, what is it and how would it influence decision making? I'm happy to provide more info if you need it. Thank you!

Aucun commentaire:

Enregistrer un commentaire