从Python中的另一个程序访问类/方法

时间:2012-11-25 05:28:21

标签: python python-2.3

我有一个程序(blackjack.py),它在其代码中访问另一个程序(cards.pygames.py)。大部分内容来自一本书,所以我无法理解它的工作原理。

下面是cards.py的代码:

class Card(object):
    """ A playing card. """
    RANKS = ["A", "2", "3", "4", "5", "6", "7",
             "8", "9", "10", "J", "Q", "K"]
    SUITS = ["c", "d", "h", "s"]
    def __init__(self, rank, suit, face_up = True):
        self.rank = rank
        self.suit = suit
        self.is_face_up = face_up

    def __str__(self):
        if self.is_face_up:
            rep = self.rank + self.suit
        else:
            rep = "XX"
        return rep

    def flip(self):
        self.is_face_up = not self.is_face_up


class Hand(object):
    """ A Hand of playing cards. """
    def __init__(self):
        self.cards = []

    def __str__(self):
        if self.cards:
            rep = ""
            for card in self.cards:
                rep += str(card) + "\t"
        else:
            rep = "<empty>"
        return rep

    def clear(self):
        self.cards = []

    def add(self, card):
        self.cards.append(card)

    def give(self, card, other_hand):
        self.cards.remove(card)
        other_hand.add(card)


class Deck(Hand):
    """ A deck of playing cards. """
    def populate(self):
        for suit in Card.SUITS:
            for rank in Card.RANKS:
                self.add(Card(rank, suit))

    def shuffle(self):
        import random
        random.shuffle(self.cards)

    def deal(self, hands, per_hand = 1):
        for round in range(per_hand):
            for hand in hands:
                if self.cards:
                    top_card = self.cards[0]
                    self.give(top_card, hand)
                else:
                    print "Can't continue deal. Out of cards!"

if __name__ == "__main__":
    print "This is a module with classes for playing cards."
    raw_input("\n\nPress the enter key to exit.")

我正在为blackjack.py编写错误检查,我需要收集到目前为止使用的卡数。我想我可以通过访问cards[]中的值数来实现这一点。问题是,我不知道如何做到这一点。

但这完全是理论上的。我也会包含'blackjack.py'代码,所以你们都可以看到我想要做的事情,并帮助我确定我的逻辑是否存在缺陷。

blackjack.py code

赞赏任何和所有输入。

1 个答案:

答案 0 :(得分:1)

虽然我不清楚你的预期结构,但你有几个选择。

首先,为了使用cards.py模块中blackjack.py的任何函数或类,您可以使用import语句导入它们。这样做有两种风格:

# blackjack.py
import cards

可以让您访问cards模块中的所有内容,并通过将其添加到cards.<name>来调用每个函数/类。所以,如果你想初始化Deck类的实例,

# blackjack.py
import cards
mydeck = cards.Deck()

另一种方式是from <X> import <Y>,它使您无需添加前缀即可访问函数和类。例如:

# blackjack.py
from cards import Deck  # or, to import everything, "from cards import *"
mydeck = Deck()

这些方法中的任何一个都会为您提供cards.Deck类的实例。

选项0

您已经可以在Deck课程中说明这一点,因为它是Hand的子类,所以每当您give一张卡片从Deck取出时s cards属性。因此,给出的卡片数量就是:

class Deck(Hand):
    # ...
    def number_cards_used(self):
         return 52 - len(self.cards)

或者,如果您无法修改cards.py,则可以通过以下方式获取给定Deck剩余的卡数:

# blackjack.py
def get_number_cards_used_from_deck(deck):
    return 52 - len(deck.cards)

使用中:

# blackjack.py
import cards
mydeck = cards.Deck()
# ...
# Do other operations with deck
# ...
cards_used = get_number_cards_used_from_deck(mydeck)

选项1

如果你可以同时隔离所有和只有那些牌,你可以实现一种方法card_count

class Hand(object):
   # ...
   # other code
   # ....

   def card_count(self):
       return len(self.cards)

然后,如果您有所有牌的列表,例如,您可以执行以下操作:

sum(map(lambda h: h.card_count(), list_of_hands))

选项2

Deck课程中,由于它是Hand的子类,因此您可以简单地保留已经发出的经常刷新的卡片的另一个运行列表。这看起来像是:

class Deck(Hand):
    # ...
    # other code
    # ...

    def __init__(self):
        self.populate()
        self.used_cards = []

    def give(self, card, other_hand):
        self.used_cards.append(card)
        super(Deck, self).give(card, other_hand)

    def number_cards_used(self):
        return len(self.used_cards)

当然还有其他方法。