Disclaimer: This may be a terribly simple question but I’m attempting to learn Python.
Essentially, I have a list of classes and given a random number, I’d like to construct a new instance of the class indexed at that random number.
#The members of the list below are class objects
SHAPES = [I_shape, J_shape, L_shape, O_shape, S_shape, T_shape, Z_shape]
I’ve discovered how to do it given a string so I guess I could just use the name attribute of the class but I’m curious if there isn’t an easier way to go about this.
Any thoughts?
Given your
SHAPESarray, you can simply call the class object:The
random.choice(SHAPES)picks one of yourI_shape,J_shape, etc, and the final()calls the constructor for that class object, just as if you had writtenI_shape()or whatever.