擅长:python、mysql、java
<p>在处理这类挑战时,这里有一个使用字典的简单方法。你知道吗</p>
<p>我在代码中添加了一些注释,请阅读。你知道吗</p>
<pre><code>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)
</code></pre>
<p>输出:</p>
<pre><code>w_bishop_1
moving w_bishop_1
</code></pre>