如何在Python中更快地生成一组对象

2024-06-16 12:17:23 发布

您现在位置:Python中文网/ 问答频道 /正文

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')

有没有更简单的方法?我也希望以后能够使用这些对象。你知道吗


Tags: 对象方法bishopqueenrookknightkingpawn
2条回答

在处理这类挑战时,这里有一个使用字典的简单方法。你知道吗

我在代码中添加了一些注释,请阅读。你知道吗

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)

输出:

w_bishop_1
moving w_bishop_1

如果遵循@kaya3's advice并重新设计ChessPiece类,则可以很容易地使用列表理解,例如(使用abbreviations并忽略数字):

color = 'W'
non_pawns = [ChessPiece(color, c) for c in 'RNBKQBNR']
pawns = [ChessPiece(color, 'P') for _ in range(8)]

相关问题 更多 >