在python中调用另一个类的方法

时间:2015-03-16 01:12:30

标签: python

如何调用属于Deck类的shuffle和takecard方法,并在Dealer类中调用它而不继承整个类。

#!/usr/bin/python
import random
class Card:
    """A card object with a suit and rank."""
    RANKS = (2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14)
    SUITS = ('Spades', 'Diamonds', 'Hearts', 'Clubs')
    def __init__(self, rank, suit):
       self._rank = rank
       self._suit = suit
    def getRank(self):
       return self._rank
    def getSuit(self):
       return self._suit
    def __str__(self):
       translate = {11:'Jack', 12:'Queen', 13:'King', 14: 'Ace'}
       r = self._rank
       if r in [11, 12, 13, 14]:
          myrank = translate[r]
       else:
          myrank = str(r)
       return myrank + " of " + self._suit
    def __lt__(self, other):
        return( self._rank < other.getRank() )
class Deck:
    def __init__(self):
        self._cards = []
        for suit in Card.SUITS:
            for rank in Card.RANKS:
                c = Card(rank, suit)
                self._cards.append(c)
    def shuffle(self):
        random.shuffle(self._cards)
    def takecard(self):
        if len(self._cards) == 0:
            return None
        else:
            #print self._cards.pop()
            return self._cards.pop()
    def __len__(self):
        return len(self._cards)
    def __str__(self):
        result = ""
        for c in self._cards:
            result = result + str(c) + '\n'
        return result
class Dealer(object):
    def __init__(self, name):
        self.name = name
    def shuffle(self):
        deck=self.deck
        self.deck.shuffle()     
    def deal(self):
        self.deck.takecard()

self.deck.takecard和self.deck.shuffle如果以这种方式声明它并不返回Deck方法: Dealer('Bob',Deck)

2 个答案:

答案 0 :(得分:1)

如果您想在创建经销商实例时传入Deck实例,请将平台作为属性附加到经销商处,然后从经销商的功能中调用套牌功能,你可以这样做:

class Dealer(object):
    def __init__(self, name, deck):
        self.name = name
        self.deck = deck
    def shuffle(self):
        self.deck.shuffle()
    def deal(self):
        return self.deck.takecard()

您传入的对象作为参数&#39; deck&#39;将需要成为Deck的一个实例:

a_deck = Deck()

答案 1 :(得分:1)

我认为您的代码存在的问题是您需要从经销商功能返回,而不仅仅是从Deck的功能返回,如下所示。您还需要在初始化程序中设置套牌:

class Dealer(object):
    def __init__(self, name, deck):
        self.name = name
        self.deck = deck

    def shuffle(self):
        deck=self.deck
        return self.deck.shuffle()
    def deal(self):
        return self.deck.takecard()

最后,您应该使用以下命令启动此类:

my_dealer = Dealer("Bob", Deck())

只使用没有括号的Deck会导致课程被提供给经销商,而不是课程的实例,这就是你想要的。