【发布时间】:2018-12-28 23:34:24
【问题描述】:
我看到括号内的方括号参数。我不知道它是什么意思以及它与正常的争论有什么不同,所以我希望对这个问题有所启发。
这里是有问题的代码行:
(我会打印整个块,因为有人可能会觉得它很有用,但重要的部分是 第一个代码 sn-p 的第 3 行和 第二行代码 sn-p 的第 2 行)
第一种情况:
def __additional_cards(self, player):
while not player.is_busted() and player.is_hitting():
self.deck.deal([player])
print(player)
if player.is_busted():
player.bust()
这一行中括号内的参数表示游戏的Player 类对象(可以有很多玩家),代码的目的是在玩家要求时发一张额外的牌。
第二种情况:
def play(self):
self.deck.deal(self.players + [self.dealer], per_hand = 2)
self.dealer.flip_first_card() # hide dealer's first card
for player in self.players:
print(player)
print(self.dealer)
在这种情况下,.deal 方法用于将起始牌发给游戏中的所有玩家以及庄家。下面是.deal方法的代码供参考:
def deal(self, hands, per_hand = 1):
for rounds in range(per_hand):
for hand in hands:
if self.cards:
top_card = self.cards[0]
self.give(top_card, hand)
如您所见,它只需要一个参数来处理应处理的“手”牌,但上面的代码使用命令+ [self.dealer] 添加了庄家,这是我第一次看到。
庄家是否只是由+ 添加到手牌中的,如果是,为什么要放在方括号中?
代码取自 Michael Dawson 的书,Python Programming for the Absolute Beginner, 3rd Edition,这是他通过解释如何制作简单的二十一点游戏来教授 OOP 的部分。 p>
【问题讨论】:
-
self.deck.deal([player])创建一个包含 1 个元素的列表并将其传递给deal函数。 -
self.deck.deal(self.players + [self.dealer], per_hand = 2)将两个列表合二为一,并将其传递给deal函数。 (假设self.players是一个列表)。 -
Deal 需要知道玩家的数量,并且由于 deal 期望手牌是一个数组,因此您正在创建一个内联数组并将其传递给函数。所以在你的例子中,你将处理 1 手牌,
player -
请始终注意,Python 中的方括号
[、]基本上用于2 目的。主要用途是创建列表,次要用途是访问 tuples、dictionaries、sets、lists 等。在您的代码中,在第一种情况下,您将 dictionary 作为函数调用中的实际参数传递。在第二种情况下,您将连接 2 个 列表。