Search code examples
pythonclassinitializationinstance

Can you initialise multiple instances of a class in one single line?


Imagine I would like to compact my code when initialising several instances of a class.

This code works:

from ipywidgets import Output,HBox
out1 = Output(layout={'border': '1px solid black'})
out2 = Output(layout={'border': '1px solid black'})
out3 = Output(layout={'border': '1px solid black'})

with out1: display('here is out1')
with out2: display('here is out2')
with out3: display('here is out3')

display(HBox([out1,out2,out3]))

Now what I want is not having to repeat three times the initialization of out1, out2, and out3.

Of course this does not work:

out1=out2=out3=Output(layout={'border': '1px solid black'})

because those three outs are the same object.

Imagine you have like 10 initialisations to do, what is a nice pythonic way to go about it without having to write 10 lines of code?

Other consultations that could not really help me: Automatically initialize multiple instance of class Can one initialize multiple variables of some type in one line? Python creating multiple instances for a single object/class


Solution

  • Create the Output objects in a list, and then you can iterate through the list:

    outputs = [Output(layout={'border': '1px solid black'}) for _ in range(3)]
    
    for i, out in enumerate(outputs, 1):
        with out:
            display(f"here is out{i}")
    
    display(HBox(outputs))