繁体   English   中英

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

[英]Accessing a class/method from another program in Python

我有一个程序( 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 代码

任何和所有的输入表示赞赏。

尽管我对您的预期结构尚不完全清楚,但您有两种选择。

首先,为了使用blackjack.py模块中cards.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以为您提供cards.Deck类的实例。

选项0

您已经可以在Deck类中知道这一点了,因为它是Hand子类,因此每次give卡片时,它都会从Deckcards属性中删除。 因此,发出的卡数将简单地为:

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)

当然,还有其他方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM