0

我正在尝试编写二十一点程序,但是当我尝试将消息从我的牌组对象发送到另一个使用 .append() 的对象时,我不断收到 AttributeError: object has no '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)

玩家参数是我使用实例化的对象元组:

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 =(
4

3 回答 3

1

问题是这条线:

        self.hand = Hand()

班内Bj_player。这使self.hand变量成为Hand实例,而不是应有的列表。roster是这些BJ_player实例的列表,因此当您调用 时deck.deal(roster),在它所说的函数中for hand in players,每个hand对象都将是这些Bj_player实例之一。

解决这个问题的最好方法是Bj_player 不要继承自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.handself.cards,它会使事情变得更加清晰!

于 2012-09-06T02:24:38.587 回答
0

例如,

a=[1,2,3]
a.append(4)

将产生:

a=[1,2,3,4]

a=a.append(4)会返回NonType对象。无法处理此对象。

所以会得到属性错误

于 2018-03-16T09:48:04.987 回答
-2

Make sure that your variables are all "hand" (lowercase) and not "Hand" (uppercase). If you look at the error, the error is saying that "Hand" (uppercase) has no attribute append. So at some point you either try to append something to the the Hand class, or you set the variable hand to the class Hand. (Note the upper and lowercase of each). Common mistake, it happens to all of us. Happy coding!

于 2012-09-06T01:29:46.047 回答