我正在尝试完成O'Reilly's Beginning Python视频系列中的一个练习。我的代码似乎(至少对我来说)从视频中复制示例,但我得到以下错误。
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
您需要调用method
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
您不是在呼叫shuffle()
。你需要括号
shuffle()
是一个类方法,因为它需要在它的名字后面加上括号。你可以不带括号访问类属性,但是方法必须有它们。