How can I make it work so the i in the for loop can be added to sq_i. So I can create multiple objects called sq_1, sq_2, sq_3, etc. enter image description here
-
1Maybe the most natural way to do what you want is to create a dictionary? docs.python.org/3/tutorial/datastructures.html#dictionariesDaLynX– DaLynX2021-12-15 10:25:24 +00:00Commented Dec 15, 2021 at 10:25
-
1Please post code as text, not as an image.Gino Mempin– Gino Mempin2021-12-15 10:25:36 +00:00Commented Dec 15, 2021 at 10:25
-
Does this answer your question? How to create multiple class objects with a loop in python?Gino Mempin– Gino Mempin2021-12-15 10:27:29 +00:00Commented Dec 15, 2021 at 10:27
Add a comment
|
2 Answers
My approach would be putting all those object in a dictionary:
class Board:
SQUARES = {}
def __init__(self, squares):
self.squares = squares
for i in range(self.squares):
Board.SQUARES[f'sq_{i}'] = Square(i+1)
I don't think playing with globals() is a good idea - I mean, like this:
for i in range(self.squares):
globals()[f'sq_{i}'] = Square(i+1)
What if the same global variable is defined somewhere else in your code, for example?
Comments
If you're just naming them sq_i where i is some integer, it sounds like you want a list.
class Board
def __init__(self, size: int):
self.squares = [Square(i+1) for i in range(size)]
Now reference with:
board = Board(16)
board.squares[0] # first square
board.squares[2] # third square
# etc...