0

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

3

2 Answers 2

0

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?

Sign up to request clarification or add additional context in comments.

Comments

0

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...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.