【问题标题】:Python TypeError unbound method must be called with instance as first argument [closed]必须使用实例作为第一个参数调用 Python TypeError 未绑定方法[关闭]
【发布时间】:2015-02-16 19:17:24
【问题描述】:

所以我正在尝试制作一个二十一点功能,该功能可以抽两张牌然后合计金额。我不断收到此错误。

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

【问题讨论】:

标签: python


【解决方案1】:

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

gameDeck.deal()

会起作用

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

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

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

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

playerHand.add(card1)

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

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

【讨论】:

  • 当我尝试我得到这个错误。 AttributeError: 'NoneType' 对象没有属性 'deal'
  • @CooperGay,修复你的缩进并在问题中放置完整的异常回溯
  • 感谢您帮助我,感谢您,我知道该怎么做。无论如何你可以帮我解决另一个问题吗?我正在尝试将我手中的牌加起来,你知道我可以这样做吗?我尝试将卡片 1 和卡片 2 附加到列表中,但它打印出一个奇怪的位置而不是总数。
  • @CooperGay,您正在一次添加到卡片中,Hands.addlist.append 方法都采用 1 个参数 - 然后您调用 playerHand.add(card1,card2).您的偏移量仍然关闭,您的代码看起来与以前没有什么不同。您显然已经投入了一些时间 - 但除非您在前进时修复代码,否则无法提供帮助。您可以发布固定代码作为答案 - 但请处理缩进!
  • 缩进是什么意思?我以为我缩进了我的代码。此外,每当执行 playerHand.add(card1,card2) 时,我都会收到一条错误消息,指出它只需要 2 个参数。因此,当我执行 playerHand.add(card1) 时,我会打印它。 &lt;Hand.Hand object at 0x01E7FC90&gt;
猜你喜欢
  • 2014-12-10
  • 2014-09-10
  • 1970-01-01
  • 1970-01-01
  • 2017-04-03
  • 2015-06-19
  • 2017-12-09
  • 2015-12-01
  • 2018-08-12
相关资源
最近更新 更多