我正试图编写一个21点程序,但当我试图将消息从我的deck对象发送到另一个使用.append()的对象时,我一直得到一个AttributeError:对象没有'append'
以下是我认为相关的代码:
class Deck(Hand):
def deal(self, players, per_hand= 1):
for rounds in range(per_hand):
for hand in players:
if self.hand:
top_card = self.hand[0]
self.give(top_card,hand)
players参数是我使用实例化的对象的元组
class Bj_player(Player,Hand):
def __init__(self,name,score= 0,status= None):
self.name = name
self.score = score
self.status = status
self.hand = Hand()
Player基类中没有任何内容,只有来自用户的一些输入。以上是我做错的地方吗?
class Hand(object):
"""a hand of cards"""
def __init__(self):
self.hand = []
def add(self, card):
self.hand.append(card)
def give(self,card,other_hand):
if self.hand:
self.hand.remove(card)
other_hand.add(card)
else:
print("EMPTY ALREADY. COULD NOT GIVE")
我去掉了str部分,把它剪掉。我得到的错误是:
line 44, in add
self.hand.append(card)
AttributeError: 'Hand' object has no attribute 'append'
我是个新手,所以解释得越简单越好。谢谢
此外,为了以防万一它有帮助,以下是我开始工作的方式:
deck = Deck() #populated and all that other stuff
total_players = Player.ask_number("How many players will there be? (1-6): ",1,6)
for player in range(total_players):
name = input("What is the player's name? ")
x = Bj_player(name)
roster.append(x)
deck.deal(roster,2) #error =(
问题出在以下行:
self.hand = Hand()
在CCD_ 1类内。这使得self.hand
变量成为Hand
实例,而不是应该的列表。roster
是这些BJ_player
实例的列表,因此当您调用deck.deal(roster)
,并且在函数中它表示for hand in players
时,每个hand
对象都将是这些Bj_player
实例中的一个。
解决此问题的最佳方法是Bj_player
0而不是从hand
继承。(实际上,不清楚为什么要从Player
继承它,也不清楚Player
类提供了什么有用的功能)。相反,让Bj_player
成为它自己的类(也许改为Player
——不那么令人困惑),并更改行
for hand in players:
if self.hand:
top_card = self.hand[0]
self.give(top_card,hand)
至
for player in players:
if self.hand:
top_card = self.hand[0]
self.give(top_card,player.hand)
另请注意:如果您将self.hand
更改为self.cards
,它将使事情变得更加清晰!
例如,
a=[1,2,3]
a.append(4)
将产生:
a=[1,2,3,4]
但是CCD_ 18将返回NonType对象。无法处理此对象。
因此将获得属性错误
确保变量都是"hand"(小写)而不是"hand"(大写)。如果您查看错误,则错误表明"Hand"(大写)没有属性append。因此,在某个时刻,您可以尝试将一些东西附加到Hand类,或者将变量Hand设置为Hand类。(注意每个的大小写)。常见的错误,它发生在我们所有人身上。编码快乐!