gpt4 book ai didi

python - 入门 Python(2.7.8) O'Reilly 视频系列练习

转载 作者:太空宇宙 更新时间:2023-11-04 10:32:56 25 4
gpt4 key购买 nike

我正在尝试完成 O'Reilly 的 Beginning Python Video 系列中的练习。我的代码(至少对我而言)看起来是为了复制视频中的示例,但是我收到以下错误。

Traceback (most recent call last):

File "blackjack.py", line 20, in <module> print(d.deal())

File "blackjack.py", line 15, in deal return self.cards.pop()

AttributeError: 'deck' object has no attribute 'cards'

这是我通常使用的代码:

import random

class deck(object):
def shuffle(self):
suits = ['Spades','Hearts','Clubs','Diamonds']
ranks = ['1','2','3','4','5','6','7','8','9','10','J','Q','K','A']
self.cards = []
for x in suits:
for y in ranks:
self.cards.append(y + x)

random.shuffle(self.cards)

def deal(self):
return self.cards.pop()

d = deck()
d.shuffle

print(d.deal())
print(d.deal())

它似乎与我的 self.cards 列表变量有关。有人有主意吗?

最佳答案

d.shuffle() # is missing  parens

您需要使用括号调用方法 d.shuffle()

In [3]: d = deck()

In [4]: d.shuffle
Out[4]: <bound method deck.shuffle of <__main__.deck object at 0x7fb8a4a04d10>>

In [5]: print(d.deal())
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-5-a5c7b7294801> in <module>()
----> 1 print(d.deal())

<ipython-input-2-0b86145ed058> in deal(self)
13
14 def deal(self):
---> 15 return self.cards.pop()

AttributeError: 'deck' object has no attribute 'cards'

In [6]: d.shuffle() # call the method

In [7]: print(d.deal()) # now all good
AHearts

关于python - 入门 Python(2.7.8) O'Reilly 视频系列练习,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25212949/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com