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

标签 python

我正在尝试完成 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/

相关文章:

python - BeautifulSoup - 如何排列数据并写入txt?

用于算法执行可视化的 Python

python - 使用 sympy 简化嵌套指数和对数

python - 从列表创建类实例

python - Pandas 中 `Series.str.contains("|")` 和 `Series.apply(lambda x:"|"in x)` 之间的区别?

python - 理解 Python 3 列出了每个元素的打印 None 值

Python Tkinter : Remove window border

Python 循环不应该工作但仍然可以工作

python - 线程只运行一次函数,并且只返回一次值?如何连续返回函数值?

python - 如何同时左右对齐结果