1
w_rook_1 = ChessPiece('w_rook_1')
w_knight_1 = ChessPiece('w_knight_1')
w_bishop_1 = ChessPiece('w_bishop_1')
w_king = ChessPiece('w_king')
w_queen = ChessPiece('w_queen')
w_bishop_2 = ChessPiece('w_bishop_2')
w_knight_2 = ChessPiece('w_knight_2')
w_rook_2 = ChessPiece('w_rook_2')
w_pawn_1 = ChessPiece('w_pawn_1')
w_pawn_2 = ChessPiece('w_pawn_2')
w_pawn_3 = ChessPiece('w_pawn_3')
w_pawn_4 = ChessPiece('w_pawn_4')
w_pawn_5 = ChessPiece('w_pawn_5')
w_pawn_6 = ChessPiece('w_pawn_6')
w_pawn_7 = ChessPiece('w_pawn_7')
w_pawn_8 = ChessPiece('w_pawn_8')

Is there an easier way to do this? I would also like to be able to use the objects afterwards.

  • 3
    You could use a list comprehension, but it looks to me like your `ChessPiece` class could do with a more fundamental redesign if you're passing in three pieces of data (colour, piece kind, piece number) as a single string. – kaya3 Dec 22 '19 at 04:00
  • Related: [How do I create a variable number of variables?](https://stackoverflow.com/q/1373164/4518341) – wjandrea Dec 22 '19 at 04:04
  • I think @kaya3 hit the nail on the head. – AMC Dec 22 '19 at 04:12

2 Answers2

2

Here is a simple approach using a dictionary when dealing with this type of challenge.

I added some comments within the code, please read.

instance_names = ['w_rook_1',
             'w_knight_1',
             'w_bishop_1',
             'w_king',
             'w_queen',
             'w_bishop_2',
             'w_knight_2',
             'w_knight_2']


class ChessPiece(object):

    def __init__(self, name):
        self.name = name
        self.move = "moving {}".format(name)

chess_objs = {}

for obj in instance_names:
    # insert instance names ex. 'w_rook_1' as the key 
    # the ChessPiece instance is set as the value
    chess_objs.setdefault(obj, ChessPiece(obj))

# here just illustrates how to access fields 
# bound to each object
print(chess_objs['w_bishop_1'].name)
print(chess_objs['w_bishop_1'].move)

outputs:

w_bishop_1
moving w_bishop_1
0

If you follow @kaya3's advice and redesign your ChessPiece class, you could use a list comprehension easily, something like this (using abbreviations and ignoring number):

color = 'W'
non_pawns = [ChessPiece(color, c) for c in 'RNBKQBNR']
pawns = [ChessPiece(color, 'P') for _ in range(8)]
wjandrea
  • 28,235
  • 9
  • 60
  • 81