必须使用instance作为第一个参数调用Python TypeError未绑定方法

时间:2015-02-15 17:15:17

标签: python

所以我试图制作一个二十一点的功能,然后抽取两张牌然后总计金额。我一直收到这个错误。

Traceback (most recent call last):
  File "C:/Users/koopt_000/PycharmProjects/BlackJack/PlayBlackJack.py", line 36, in <module>
game()
  File "C:/Users/koopt_000/PycharmProjects/BlackJack/PlayBlackJack.py", line 29, in game
    card1 = Deck.deal()
TypeError: unbound method deal() must be called with Deck instance as first argument (got nothing instead)   

这是我的完整代码。

class Card(object):

    '''A simple playing card. A Card is characterized by two 
    components:
    rank: an integer value in the range 2-14, inclusive (Two-Ace)
    suit: a character in 'cdhs' for clubs, diamonds, hearts, and
    spades.'''

    #------------------------------------------------------------

    SUITS = 'cdhs'
    SUIT_NAMES = ['Clubs', 'Diamonds', 'Hearts', 'Spades']

    RANKS = range(2,15)
    RANK_NAMES = ['Two', 'Three', 'Four', 'Five', 'Six',
              'Seven', 'Eight', 'Nine', 'Ten', 
              'Jack', 'Queen', 'King', 'Ace']
    RANK_VALUES = [99, 99, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11]
    #------------------------------------------------------------

    def __init__(self, rank, suit):

        '''Constructor
        pre: rank in range(1,14) and suit in 'cdhs'
        post: self has the given rank and suit'''

        self.rank_num = rank
        self.suit_char = suit


    #------------------------------------------------------------

    def getSuit(self):

        '''Card suit
        post: Returns the suit of self as a single character'''

        return self.suit_char

    #------------------------------------------------------------

    def getRank(self):

        '''Card rank
        post: Returns the rank of self as an int'''

        return self.rank_num

    #------------------------------------------------------------

    def getCardValue(self):
        value = self.RANK_VALUES[self.rank_num]
        return value

    #------------------------------------------------------------
    def suitName(self):

        '''Card suit name
        post: Returns one of ('clubs', 'diamonds', 'hearts',
              'spades') corrresponding to self's suit.'''

        index = self.SUITS.index(self.suit_char)
        return self.SUIT_NAMES[index]        

    #------------------------------------------------------------

    def rankName(self):

        '''Card rank name
        post: Returns one of ('ace', 'two', 'three', ..., 'king')
              corresponding to self's rank.'''

        index = self.RANKS.index(self.rank_num)
        return self.RANK_NAMES[index]

    #------------------------------------------------------------

    def __str__(self):

        '''String representation
        post: Returns string representing self, e.g. 'Ace of Spades' '''

        return self.rankName() + ' of ' + self.suitName()

    #------------------------------------------------------------

from random import randrange
from Card import Card
from Hand import Hand


class Deck(object):

def __init__(self):
    '''This creates the deck of cards, un-shuffled.'''
    cards = []
    for suit in Card.SUITS:
        for rank in Card.RANKS:
            cards.append(Card(rank,suit))
    self.cards = cards

def size(self):
    '''How many cards are left.'''
    return len(self.cards)

def deal(self):
    '''Deals a single card.
    Pre: self.size() > 0
    Post: Returns the next card in self, and removes it from self.'''
    return self.cards.pop()

def shuffle(self):
    '''This shuffles the deck so that the cards are in random order.'''
    n = self.size()
    cards = self.cards
    for i,card in enumerate(cards):
        pos = randrange(i,n)
        cards[i] = cards[pos]
        cards[pos] = card

def takeAHit(self, whatHand):
    aCard = self.deal()
    whatHand.addCard(aCard)
def __str__(self):
    if self.size() == 52:
        return 'The Deck is Full'
    elif self.size() > 0:
        return 'The Deck has been Used'
    else:
        return 'The Deck is Empty'


from Card import Card

class Hand(object):

"""A labeled collection of cards that can be sorted"""

#------------------------------------------------------------

def __init__(self, label=""):

    """Create an empty collection with the given label."""

    self.label = label
    self.cards = []

#------------------------------------------------------------

def add(self, card):

    """ Add card to the hand """

    self.cards.append(card)

#------------------------------------------------------------

def handTotal(self):
    totalHand = 0
    aceAmount = 0

    for c in self.cards:
        if c.getRank() == 14:
            aceAmount += 1
            totalHand +=c.getCardValue()
    while aceAmount > 0:
        if totalHand > 21:
            aceAmount -= 1
            totalHand -= 10
        else:
            break
    return totalHand

def __str__(self):
 if self.cards == []:
    return "".join([(self.label), "doesn't have any cards."])
    tempStringList = [ self. label, "'s Cards,  "]
    for c in self.cards:
        tempStringList.append(str(c))
        tempStringList.append(" , ")

        tempStringList.pop()
        tempStringList.append(" . ")

        return "".join(tempStringList)




from Deck import Deck
from Card import Card
from Hand import Hand

def rules(playerTotal, dealerTotal):
if playerTotal > 21:
    print "You busted!"
    if dealerTotal == 21:
        print 'To make it worse, dealer has 21.'
elif dealerTotal > 21:
    print "The Dealer has busted. You win!"
elif playerTotal == 21:
    print " You got 21! So you win!"
    if dealerTotal == 21:
        print "The Dealer also got 21. Tough Break."
elif dealerTotal == 21:
    print "The Dealer got 21! Tough Break, you lose!"
else:
    if playerTotal > dealerTotal:
        print "You beat the Dealer! You got lucky punk."
    if playerTotal == dealerTotal:
        print "It is a push, no one wins!"
    else:
        print "Dealer wins! Better luck next time loser."
def game():
    gameDeck = Deck()
    gameDeck = gameDeck.shuffle()
    player = raw_input("What is your name?")
    card1 = Deck.deal()
    card2 = Deck.deal()
    playerHand = Hand(player)
    playerHand = playerHand.add(card1,card2)
    print playerHand.totalHand()
    print gameDeck

我有什么遗漏因为我对此感到困惑。 编辑:我现在一直收到这个错误。

Traceback (most recent call last):
  File "C:/Users/koopt_000/PycharmProjects/BlackJack/PlayBlackJack.py", line 33, in <module>
    print gameDeck.deal()
AttributeError: 'NoneType' object has no attribute 'deal'

Process finished with exit code 1

1 个答案:

答案 0 :(得分:3)

Deck 是一个类 - 而不是一个对象

gameDeck.deal()

将起作用

让我详细说明一下 - 调用类作为函数 Deck()创建类的对象,通过它可以调用类方法 - 如上所述。

Deck 是对类的引用 - 只有classmethods可以通过类引用调用。

关于“参数数量”的快速解释。与C ++ this 不同,Python在方法中没有对象实例的保留字。你必须在方法定义中明确地定义它 - 无处不在的 self (实际上是一个约定,而不是保留字)。

所以,当你调用一个对象的方法时 - 例如

playerHand.add(card1)

playerHand 是第一个参数, card1 是第二个参数

关于缩进 - 它们可能在您的代码中正常,但它们看起来并不正确。也许,你的代码中有标签?那些必须用空格代替。谷歌如何