即使提供参数,也会丢失参数错误

时间:2017-03-24 23:41:13

标签: python python-3.x

我在Python 3.5中编写了一个基于文本的Blackjack游戏,并创建了以下类和相应的方法:

import random

class Card_class(object):

    def __init__(self):            
        pass

    def random_card(self):
        suites = ['clubs', 'spades', 'diamonds', 'hearts']
        denomination = ['ace', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'jack', 'queen', 'king']
        card = (suites[random.randint(0, 3)], denomination[random.randint(0, 13)])     
        return card

    def card_check(self, card, cards_distributed):       
        if card not in cards_distributed:
            cards_distributed.append(card)                
            return True        
        else:                
            return False


class Player_hand(object):

    def __init__(self):            
        pass

    def cards_held(self, card, cards_holding):            
        cards_holding.append(card)            
        return cards_holding

class Distribute_class(object):

    def __init_(self):
        pass

    def initial_card_distribute(self, cards_distributed, player_cards_holding = [], cards_held = 0):

        player = ''
        while cards_held < 2:
            player = Card_class()
            result_card = player.random_card()

            if not player.card_check(result_card, cards_distributed):
                continue
            else:
                Player_hand.cards_held(result_card, player_cards_holding)
                break

        return player_cards_holding

我尝试使用

测试我的代码
distributed_cards = []
player1 = Distribute_class()
player1_hand = player1.initial_card_distribute(distributed_cards)
player1_hand

但是我给出了以下错误:

TypeError: cards_held() missing 1 required positional argument:
'cards_holding'

显示错误的终端窗口表示错误来自上面列出的最终类Player_hand.cards_held(result_card, player_cards_holding)中包含Distribute_class的行。这行不能识别我给它在同一个类中的方法中定义的默认参数player_cards_holding = []吗?或者是否存在某种其他问题,即产生错误的方法&#34; cards_held&#34;是从另一个类调用的?

1 个答案:

答案 0 :(得分:1)

你从根本上误解了课程的运作方式。问题是这一行:

Player_hand.cards_held(result_card, player_cards_holding)

使用实例方法cards_held而不传递实例(在方法签名中为self)。因此,要使用该方法初始化Player_hand对象,如下所示:ph = Player_hand()然后使用

ph.cards_held(result_card, player_cards_holding)

幕后发生的事情是ph隐式传递给cards_held

另外,watch out for the mutable default argument并且除非您了解它是如何工作的,否则不要使用它。

但从根本上说,你正在使用类但不正确。你的课程都没有数据属性!所有这些都可以只是模块级功能,也可以正常工作。